How does constant lookup and scoping work in Ruby?

Last updated 30 June 2026

  • Ruby checks lexical scope first (Module.nesting: the enclosing module/class blocks as written), then the ancestor chain, then top-level Object.

  • class A::B and nested module A; class B create different nesting, so constant lookup can differ.

  • Explicit Foo::BAR skips lexical scope and searches only Foo and its ancestors.

  • https://noelrappin.com/2023/10/better-know-a-ruby-thing-22-constants/
  • https://docs.ruby-lang.org/en/3.4/syntax/modules_and_classes_rdoc.html
  • https://blog.appsignal.com/2021/01/13/using-mixins-and-modules-in-your-ruby-on-rails-application.html
  • https://cirw.in/blog/constant-lookup.html
All Ruby interview questions