liveBook · Manning

Double-colon constant lookup token

As explained in The Well-Grounded Rubyist, Fourth Edition

Constant lookup notation is Ruby syntax using a double colon to access a constant in a class or module.

Ruby uses :: to reach a constant defined inside a class or module. For example, Ticket::VENUES looks up VENUES inside Ticket after the class definition has closed. section 3.7.1

Looking up a class constant

class Ticket VENUES = ["Convention Center", "Fairgrounds", "Town Hall"] end puts Ticket::VENUES The same connector accesses constants in modules, as in Math::PI. section 3.7.1

The notation also chains nested names. Tools::Hammer identifies Hammer inside Tools, and Tools::Hammer.new creates an instance of that nested class. Such chains provide namespaces, allowing Tools::Hammer and Piano::Hammer to coexist without name conflicts. section 4.4.2

Read the notation with these cautions:

  • A chained name does not reveal whether the final element is a class, module, or ordinary constant; source or documentation supplies that information. section 4.4.2
  • The connector performs constant lookup; it does not imply that every referenced constant is immutable. section 3.7.1
class Ticket
  VENUES = ["Convention Center", "Fairgrounds", "
➥ Town Hall"] #1
end
puts "We've closed the class definition."
puts "So we have to use the path notation to reach the constant."
puts "The venues are:"
puts Ticket::VENUES

Trace a constant after its class definition closes, then inspect it through the class-qualified path. section 3.7.1

module Tools
  class Hammer
  end
end

See the nested module and class declarations that make Tools::Hammer possible. section 4.4.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains direct and chained lookup with examples, then stops short of a detailed constant-resolution algorithm.
Examples
Uses Ticket::VENUES, Math::PI, and Tools::Hammer to demonstrate qualified constant access and instantiation.
What it assumes
Assumes familiarity with Ruby classes and constants while establishing modules and namespaces through concrete examples.
What you can do after
Apply it via Ruby's :: syntax to retrieve qualified constants and instantiate nested classes.
How it connects
Connects constants with classes, modules, nested classes, and namespaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.