Ruby : Ruby dot “.” and double Colon “::” Operators

Ruby dot “.” and double Colon “::” Operators:

You call a module method by preceding its name with the module’s name and a period, and you reference a constant using the module name and two colons.

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.

Remember: in Ruby, classes and methods may be considered constants too.

You need just to prefix the :: Const_name with an expression that returns the appropriate class or module object.

If no prefix expression is used, the main Object class is used by default.

Here are two examples:

MR_COUNT = 0        # constant defined on main Object class
module Foo
  MR_COUNT = 0
  ::MR_COUNT = 1    # set global count to 1
  MR_COUNT = 2      # set local count to 2
puts MR_COUNT       # this is the global constant
puts Foo::MR_COUNT  # this is the local "Foo" constant


module B
 def self.print
 puts 'its outer B print'
module A
 def self.get_print_of_inner_B
 def self.get_print_of_outer_B
module A::B
 def self.print
 puts 'its inner B of A print'

When you paste the code above in IRB, you get

2.2.1 :01 > A.get_print_of_inner_B
its inner B of A  print
 => nil 
2.2.1 :02 > A.get_print_of_outer_B
its outer B print
 => nil 



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s