What is the difference in dot operator, colon operator and scope resolution operator in Ruby?
Where and why are they used?
The dot operator separates an object and a method belonging to that object, for example "Hello".reverse
or
def self.my_singleton_method
end
This single colon isn't really an operator. It can be used in ruby 1.8 instead of then
in an if
or case/when
statement. In ruby 1.9 it can be used in hash literals, e.g. {A : 65}
. It precedes an identifier to form a Symbol, e.g. :red
, and it's used in the ternary condition operator ?:
.
The double colon operator is the scope resolution operator. It specifies in which class or module you reference a constant. Note that classes and modules are themselves constants.
module MyModule
class Object
end
p Object # prints "MyModule::Object"
p ::Object # prints "Object"
end
Preceding a constant with ::
means that you take it from the outer, or global, scope.
The .
is used for method calls
The :
is used to define symbols
The @
@@
$
is used to denote a scope
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With