HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

What is Ruby's double-colon `::`?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
colonrubydoublewhat

Problem

What is this double-colon ::? E.g. Foo::Bar.

I found a definition:


The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.

What good is scope (private, protected) if you can just use :: to expose anything?

Solution

:: is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:

module SomeModule
    module InnerModule
        class MyClass
            CONSTANT = 4
        end
    end
end


You could access CONSTANT from outside the module as SomeModule::InnerModule::MyClass::CONSTANT.

It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .).

Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes

Code Snippets

module SomeModule
    module InnerModule
        class MyClass
            CONSTANT = 4
        end
    end
end

Context

Stack Overflow Q#3009477, score: 447

Revisions (0)

No revisions yet.