According to the documentation mod.const_get(sym) “Returns the value of the named constant in mod.”
I also know that const_get by default may look up the inheritance chain of the receiver. So the following works:
class A; HELLO = :hello; end
class B < A; end
B.const_get(:HELLO) #=> :hello
I also know that classes in Ruby subclass Object, so that you can use const_get to look up ‘global’ constants even though the receiver is a normal class:
class C; end
C.const_get(:Array) #=> Array
However, and this is where i’m confused — modules do not subclass Object. So why can I still look up ‘global’ constants from a module using const_get? Why does the following work?
module M; end
M.const_get(:Array) #=> Array
If the documentation is correct – const_get simply looks up the constant defined under the receiver or its superclasses. But in the code immediately above, Object is not a superclass of M, so why is it possible to look up Array ?
Thanks
You are correct to be confused… The doc didn’t state that Ruby makes a special case for lookup of constants in
Modulesand has been modified to state this explicitly. If the constant has not been found in the normal hierarchy, Ruby restarts the lookup fromObject, as can be found in the source.Constant lookup by itself can be bit confusing. Take the following example:
In both places, though, accessing
Objectlevel constants likeArrayis fine (thank god!). What’s going on is that Ruby maintains a list of “opened Module definitions”. If a constant has an explicit scope, sayLookHereOnly::Foo, then onlyLookHereOnlyand its included modules will be searched. If no scope is specified (likeFooin the example above), Ruby will look through the opened module definitions to find the constantFoo:M::N, thenMand finallyObject. The topmost opened module definition is alwaysObject.So
M::N.const_get :Foois equivalent to accessingFoowhen the opened classes are onlyM::NandObject, like in the last part of my example.I hope I got this right, coz I’m still confused by constant lookups myself 🙂