ddeveloperr
10/26/2015 - 7:59 AM

ruby Colon access operator explained with example

ruby Colon access operator explained with example

# Double Colon (::) is namespace resolution. It can also call Class Level Constants. So when you do this:

MyModule::MyClass::MySubClass
MyModule::MyClass::MySubClass::CONSTANT

# it is calling the name space of:
module MyModule
    class MyClass
        class MySubClass
            CONSTANT = 'test'
        end
    end
end

# This differs from Dot Operators (.) in that with Dot you are calling a property or method.
# This will call a method
MyModule::MyClass::MySubClass.new
MyModule::MyClass::MySubClass.run
MyModule::MyClass::MySubClass.property = test
MyModule::MyClass::MySubClass.property #=> test

#This either initializes the object or calls a class method:
module MyModule
    class MyClass
        class MySubClass
            CONSTANT = 'test'
            attr_accessor :property
            def initialize
                # stuff
            end
            def property=(property)
                @property = property
            end
            def property
                @property
            end
            def self.run
                # more stuff
            end
        end
    end
end