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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework