What is a root object? If you mean the main object, you cannot set a constant at this level:
TOPLEVEL_BINDING.eval('self').const_set("MY_CONSTANT", "value")
If you mean an Object , do the following:
Object.const_set("MY_CONSTANT", "value") # => "value"
then you can use it on main or at any other level:
::MY_CONSTANT # => "value"
Adding another confirmation
We can set the constant using Kernel or using Object , and in both cases the constant will be accessible from the root namespace:
Kernel.const_set("KERNEL_CONSTANT", "value") Object.const_set("OBJECT_CONSTANT", "value") puts !!(defined? ::KERNEL_CONSTANT) # => true puts !!(defined? ::OBJECT_CONSTANT) # => true
But if we set the constant to the root namespace, that constant will actually be set to Object , and not to Kernel :
::ROOT_CONSTANT = "value" puts !!(defined? Object::ROOT_CONSTANT) # => true puts !!(defined? Kernel::ROOT_CONSTANT) # => false
Mal Skrylev
source share