When I have a module like this:
module MyModule
class MyClass
end
end
I can access/modify MyModule
referencing it:
MyModule.const_set("MY_CONSTANT", "value")
But what about the Root
namespace, the ::
one?, I'm looking for something like:
::.const_set("MY_CONSTANT", "value")
The const_set
thing is just an example, please don't try to solve this concrete situation but the way of actually making reference to the Root
namespace
Namespace in Ruby allows multiple structures to be written using hierarchical manner. Thus, one can reuse the names within the single main namespace. The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter.
You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module.
The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class.
In Ruby, modules are somewhat similar to classes: they are things that hold methods, just like classes do. However, modules can not be instantiated. I.e., it is not possible to create objects from a module. And modules, unlike classes, therefore do not have a method new .
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With