Top-level constants in BasicObject

Posted . Visible to the public.

If you want to access top-level constants inside a BasicObject class, you need to prefix them with ::.

This will not work

class Foo < BasicObject
  def bar
    Hash.new
  end
end

Foo.new.bar # => NameError: uninitialized constant Foo::Hash

You need to explicitly write ::Hash.

The reason is that top-level constants are internally attached to Object, so Hash is not in the lookup chain inside a BasicObject.

Tobias Kraze
Last edit
Tobias Kraze
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2016-04-25 07:50)