Ruby dot and double colon operators
Ruby . and :: operators
In Ruby you call a module method by preceding its name with the module's name and a period and you refer a constant using the module name and two colons.
The :: is a unary operator and is used to access (anywhere outside the class or module) constants, instance methods and class methods defined within a class or module.
Note: In Ruby, classes and methods may be considered constants too.
You must 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 is an example :
X = 0 # constant defined on main Object class
module Calculate
X = 0
::X = 10 # set global count to 10
X = 20 # set local count to 20
end
puts X # this is the global constant
puts Calculate::X # this is the local "Calculate" constant
Output:
abc.rb:4: warning: already initialized constant X abc.rb:1: warning: previous definition of X was here abc.rb:5: warning: already initialized constant Calculate::X abc.rb:3: warning: previous definition of X was here 10 20
Previous:
Ruby Defined Operators
Next:
Ruby If Else Unless Statement
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/ruby/ruby-dot-and-double-colon-operators.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics