Ruby how to refer to Root namespace?

When I have a module like this:

module MyModule class MyClass end end 

I can access / modify MyModule by referencing it:

 MyModule.const_set("MY_CONSTANT", "value") 

But what about the namespace Root , :: one ?, I am looking for something like:

 ::.const_set("MY_CONSTANT", "value") 

const_set thing is just an example, please don't try to solve this specific situation, but the way to actually refer to the root namespace

+7
ruby main
source share
3 answers

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") # 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 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 
+8
source share

There is no such thing as a Root module, however you can get some pretty similar thing working in the Object class:

 def bar 'bar' end class A def bar 'not bar' end def test bar end def test2 Object.bar end end A.new.test #=> 'not bar' A.new.test2 #=> 'bar' 

Here you can read the main object: http://banisterfiend.wordpress.com/2010/11/23/what-is-the-ruby-top-level/

0
source share

Ruby does not have a root module.

You can define a module in the top-level namespace as follows:

 ::MY_CONSTANT = "value" 

If for some reason you should use const_set , you can do:

 module Hi Kernel.const_set("X", "3") end puts X # => 3 

Kernel is placed in the top-level namespace, so you effectively define a constant in the global namespace in this way.

-one
source share

All Articles