What is the root object? If you mean main
object, you can't set constant at this level:
TOPLEVEL_BINDING.eval('self').const_set("MY_CONSTANT", "value")
# NoMethodError: undefined method `const_set' for main:Object
# from (irb):71
# from /home/malo/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
If you mean Object
object, do as follows:
Object.const_set("MY_CONSTANT", "value")
# => "value"
then you can use at the main
, or at any other level:
::MY_CONSTANT
# => "value"
Adding another confirmation
We can set a 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 a constant in the root namespace this constant is actually set in Object
and not in Kernel
:
::ROOT_CONSTANT = "value"
puts !!(defined? Object::ROOT_CONSTANT) # => true
puts !!(defined? Kernel::ROOT_CONSTANT) # => false