Home

Meaning of Ruby's double-colon '::'

03 Apr 2022 - Ronald

Learn the meaning of Ruby’s double-colon ‘::’, also called constant lookup token.

Let’s start with a simple example, a class with a constant. The way to access the constant is shown below:

class C
  X = 1
end

puts C::X
# => 1

If you have nested classes and modules, access a constant in the same way:

module M
  class C
    class D
      X = 1
    end
  end
end

puts M::C::D::X
# => 1

Constants are identified relative to the point of execution:

module M
  class C
    class D
      module N
        X = 1
      end
    end
    puts D::N::X
  end
end

Namespaces

As you may know, modules in Ruby are bundles of methods and constants that you can mix in classes. But you can also use modules to create namespaces.

In the following example, class C “belongs to namespace” M:

module M
  class C
  end
end

To create an instance of class C defined inside module M, you use the constant lookup token (::) to point the way to the name of the class (classes are also constants):

h = M::C.new

Use of ‘::’ at the beginning of the path

It’s also possible to create absolute lookup paths:

::String.new("Hello")

The :: in front of a constant means “start the search for this at the top level.”

The following example demonstrates how to use an absolute lookup path to access a constant (a class in this case.)

# top level C class
class C
  def c
    puts 'Top level C'
  end
end

class D
  # nested C class
  class C 
    def top_level_c
      ::C.new.c
    end
  end
end

D::C.new.top_level_c
# => Top level C

As you can see from the result of running this code, ::C.new.c refers to the top level C class.