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?
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.
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