Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operators in Ruby

Tags:

ruby

What is the difference in dot operator, colon operator and scope resolution operator in Ruby?

Where and why are they used?

like image 846
Aung Thu Kyaw Avatar asked Dec 16 '22 13:12

Aung Thu Kyaw


2 Answers

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.

like image 118
jonas054 Avatar answered Jan 04 '23 15:01

jonas054


The . is used for method calls

The : is used to define symbols

The @ @@ $ is used to denote a scope

like image 29
isakkarlsson Avatar answered Jan 04 '23 14:01

isakkarlsson