Frage

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

War es hilfreich?

Lösung

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

Andere Tipps

There is no such a thing like a Root module, however you can get some quite similar thing operating on 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'

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

There is no such thing as a root module in Ruby.

You can define a module in the top-level namespace like this:

::MY_CONSTANT = "value"

If for some reason you have to use const_set you can do:

module Hi
  Kernel.const_set("X", "3")
end

puts X # => 3

Kernel is mixed-in into the top-level namespace so you're effectively defining a constant in the global namespace this way.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top