Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does numerical objects in Ruby exclude dot notation?

I notice that dot notation is required in a majority of the cases to call an object's method. I assume the dot is used to connect the object with the method name, but in arithmetic operations, there is a space between the number object and its operation method. For example,

7.-(5)

uses dot notation and can also be written as

7 - 5

with optional spaces in between the operator and the operands. How is it able to perform the method call?

like image 664
Lemuel Uhuru Avatar asked Mar 25 '23 08:03

Lemuel Uhuru


1 Answers

Syntactic Sugar for Special Methods good source to know all syntactic sugar of ruby.

The all are below are same in Ruby.

2 + 3   #=> 5
2.+(3)  #=> 5
2.+ 3 #=> 5

so when you write 2 + 3, it is happening internally as 2.+(3) or 2.+ 3

As everything in Ruby is an object. and here 2 also a Fixnum object. With . we are calling object 2 's + method,that's it.

2.class #=> Fixnum
2.instance_of? Fixnum #=> true
2.respond_to? :+  #=> true

Another example follows below:

"a" + "b" #=> "ab"
"a".+"b" #=> "ab"
"a".respond_to? :+ #=> true

respond_to returned true - this is because String class has the concatenation method +. Being a object of String class 'a' could call + method by passing b as an argument to that method.

like image 175
Arup Rakshit Avatar answered Mar 31 '23 17:03

Arup Rakshit