Read more

Top-level constants in BasicObject

Tobias Kraze
April 25, 2016Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Tobias Kraze to makandra dev (2016-04-25 09:50)