Constant Lookup
When a constant is referenced without any qualifying namespace, the Ruby interpreter must find the appropriate definition of the constant. To do so, it uses a name resolution algorithm, just as it does to find method definitions. However, constants are resolved much differently than methods.
Ruby first attempts to resolve a constant reference in the lexical
scope of the reference. This means that it first checks the class or
module that encloses the constant reference to see if that class or
module defines the constant. If not, it checks the next enclosing class
or module. This continues until there are no more enclosing classes or
modules. Note that top-level or “global” constants are not considered
part of the lexical scope and are not considered during this part of
constant lookup. The class method Module.nesting returns the list of
classes and modules that are searched in this step, in the order they
are searched.
If no constant definition is found in the lexically enclosing
scope, Ruby next tries to resolve the constant in the inheritance
hierarchy by checking the ancestors of the class or module that referred
to the constant. The ancestors method
of the containing class or module returns the list of classes and
modules searched in this step.
If no constant definition is found in the inheritance hierarchy, then top-level constant definitions are checked.
If no definition can be found for the desired constant, then the
const_missing method—if there is one—of the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access