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
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
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 ...