Ruby Constant Lookup
Update (2025-08): Since Ruby 2.5.0, referencing a top-level constant through a nested class or module raises a
NameErrorinstead of printing a warning. This post was written in 2017 against Ruby 2.4 and describes the behavior prior to that change.
I’ve been writing Ruby on Rails for a little over a year now. As I’ve started peeking behind the curtain of Rails’ magic, I’ve also begun noticing some of its rough edges and warts. Rails is the 800-pound gorilla of the Ruby world, yet philosophically it sometimes feels at odds with Ruby itself. To keep a record of the traps I’ve stepped into over the past year (or the docs I didn’t read carefully enough)—and to pull together what I’ve seen, thought about, and dug into—I’m starting this series with constant lookup.
Constant Definitions
To understand how Ruby looks up constants, we first need to know how it defines and stores them.
# module is a constant
module Namespace
# class is also a constant
class Something
# still a constant
SOME_VALUE = true
end
endRuby has lexical scope, but unlike most languages, the module and class keywords each open a brand-new lexical scope. In the snippet above, SOME_VALUE is defined inside the scope of class Something. Where does Ruby actually store it?
In Ruby MRI, every class or module is backed by an RClass C struct, and constants defined inside that scope are recorded in a constant table on that struct. In irb, we can inspect the constants stored directly on Something by calling Namespace::Something.constants(false)1:
irb(main):008:0> Namespace::Something.constants
=> [:SOME_VALUE]By the same token, class Something is itself a constant defined in the scope opened by module Namespace.
Follow that thread one step further: where is the top-level module Namespace stored? In short, top-level constants live in the constant table of Object. Calling Object.constants(false) gives you all the top-level constants you’ve defined.
Module.nesting
Whenever Ruby encounters a module or class keyword, it opens a new lexical scope, forming a chain of nested scopes.
In Ruby’s C implementation, the current lexical scope is represented by the rb_cref_t struct2:
typedef struct rb_cref_struct {
VALUE flags;
const VALUE refinements;
const VALUE klass;
struct rb_cref_struct * const next;
const rb_scope_visibility_t scope_visi;
} rb_cref_t;Here, klass points to the class or module of the current scope, and next points to the enclosing scope’s cref struct. This linked list traces the lexical hierarchy from the current scope all the way out to the top level. In irb, we can inspect the klass values along this chain with Module.nesting:
module A
class B
class C
p Module.nesting # => [A::B::C, A::B, A]
p B == ::A::B # => true
end
end
endWhen we reference the constant B inside C, Ruby walks Module.nesting in order: it checks the constant table of A::B::C (not found), then A::B (still not found), and finally checks A, where it finds B.
Now, can you guess what the code below outputs?
module A; end
module A::B
class C
p Module.nesting # => [A::B::C, A::B]
p B == ::A::B # => ???
end
endIt raises NameError: uninitialized constant A::B::C::B. Because B lives in A’s constant table—and compact-style module A::B never opened A’s scope—A isn’t in Module.nesting, so Ruby can’t find B along the lexical scope chain.
Ancestors
Walking the lexical scope chain alone isn’t enough; we also expect subclasses to inherit constants from their superclasses.
class Base
CONST = 'constant in base'
end
class Sub < Base
p CONST # => constant in base
end
p Sub::CONST # => constant in baseAs you’d expect in an object-oriented language, Ruby also searches the inheritance chain. Specifically, Ruby walks up the ancestor chain of the current scope’s class or module3, which we can inspect via Sub.ancestors.
That raises an obvious question: if a constant is defined in both an enclosing lexical scope and a superclass, which one wins? Let’s run a quick test:
class Base
CONST = 'constant in base'
end
module Namespace
CONST = 'constant in namespace'
class Sub < Base
p CONST # => 'constant in namespace'
end
p Sub::CONST # => 'constant in base'
endThe first line, p CONST, prints 'constant in namespace', which tells us Ruby checks the lexical scope chain (Module.nesting) before falling back to the ancestor chain.
The second line, p Sub::CONST, looks similar but prints 'constant in base'. When evaluating Sub::CONST, Ruby first resolves Sub and then looks up CONST scoped to Sub. At that point, lexical scope is out of the picture—Ruby jumps straight to Sub’s ancestor chain. These two forms of lookup also behave differently when top-level constants are involved, as we’ll see next.
Toplevel Constants?
Wait—didn’t we miss something? Module.nesting never includes the top-level scope, so how does Ruby resolve top-level constants? Does it have a special rule for them?
Yes and no.
Believe it or not, Ruby finds top-level constants through the inheritance chain. Remember where top-level constants live? Inside Object.
class MyClass
p Math::PI
endWhen we reference the top-level constant Math inside MyClass, Ruby finds it simply by walking MyClass.ancestors until it hits Object.
Problem solved! We don’t even need a new rule for top-level constant lookup. Case closed!
Or is it?
If you know Ruby’s class hierarchy well, you might remember that Object isn’t actually at the very top of the tree. Worse yet, when we define a module—which we use as a namespace all the time—its ancestor chain often contains nothing but the module itself!
module Namespace; end
p Namespace.ancestors # => [Namespace]That’s not great. We obviously need to access top-level constants from inside a module. So Ruby tacks an extra rule onto the ancestor search: if the current scope is a module, search Object’s ancestors after searching the module’s own ancestors. Everyone’s happy—and as for classes that sit above Object in the hierarchy, like Kernel and BasicObject, we don’t really care (in fact, that’s almost certainly intentional).
That’s also why BasicObject is often used as a clean-room scope:
class BasicObject
p String # => NameError: uninitialized constant BasicObject::String
endConstants Lookup, The Ugly
Now take a look at this snippet:
class Hash
p String == Hash::String
endBeing able to reference a top-level constant (String) inside a class scope (Hash) is completely expected. But what on earth is Hash::String? There’s obviously no such class. Yet instead of raising a NameError, Ruby gives us this:
(irb):21: warning: toplevel constant String referenced by Hash::String
trueWait, what? How is that possible?
The reason is simple: once both lookups fall back to the ancestor chain, they do almost the exact same thing. Both look for String in Hash, fail to find it, and walk up Hash.ancestors—which inevitably leads both of them to Object.
Does this cause real bugs?
It does—especially with Rails autoloading. Because classic Rails autoloading relies on const_missing, if a top-level constant with the same name has already been loaded, Ruby can silently resolve your namespaced constant to the top-level one, emitting nothing more than a single warning buried in an endless stream of logs. The example below is taken straight from the Rails Guides4:
# app/models/hotel.rb
class Hotel
end
# app/models/image.rb
class Image
end
# app/models/hotel/image.rb
class Hotel
class Image < Image
end
end$ bin/rails r 'Image; p Hotel::Image' 2>/dev/null
Image # NOT Hotel::Image!Footnotes
-
There are two
constantsmethods (Module.constantsandModule#constants); here we mean the instance method onModule. Passinginherit = falselists only the constants stored in that class or module’s own constant table. ↩ -
Based on Ruby 2.4. Prior to Ruby 2.3, this was represented by the
NODEstruct. ↩ -
Note that the ancestor lookup starts from the class or module of the current lexical scope, not
self.class. ↩ -
Thankfully, Ruby 2.5.0 finally turned this warning into an actual
NameError. ↩
