← Back to Ruby Operators

Double Colon

The :: (double colon) syntax is used to define a namespace or reference a namespace. It can also be used to call a method.

Module Namespacing

We can define a namespace for our modules, classes, and constants through nesting.

MY_CONSTANT = "Outer Space"

module OuterModule
  module InnerModule
    class MyClass
      MY_CONSTANT = "World"

      def self.hello
        puts "Hello, #{MY_CONSTANT}"
        puts "Hello, #{::MY_CONSTANT}"
        puts ancestors
      end
    end
  end
end

OuterModule::InnerModule::MyClass.hello

puts OuterModule::InnerModule::MyClass::MY_CONSTANT

A couple things to note in this code block:

  • Once defined, we can traverse the namespace chain to call a method — OuterModule::InnerModule::MyClass.hello
  • In the same way, we can traverse it to reference a constant — OuterModule::InnerModule::MyClass::MY_CONSTANT
  • If there a global entity that we are trying to reference outside the current namespace that conflicts, we can escape the namespace with a leading double-colon — ::MY_CONSTANT

As long as a module already exists, we can use it to define a namespaced entity.

module OverHere
end

class OverHere::MyClass
  def self.hello
    puts ancestors
  end
end

Calling A Method

Oddly enough, we can call a method with :: instead of the typical .. I wouldn't recommend doing this in any actualy code though.

> 'html'::upcase
=> "HTML"

References