Search code examples
rubyoperatorsoperator-overloadinganonymous-methodsaddition

What happens when we use operators in ruby


As i understand when we add two numbers in ruby a '+' method is called on the current object with parameter as the the next object.

>> 2 + 3
=> 5



>> 2.+(3)
=> 5

How are these two examples same is it possible that we can call methods on objects without the dot operator ? How is it happening in the first example ? if that is the case the could 3 be an method method called on '+' method ? (It doesn't even make sense)


Solution

  • Ruby knows that + is an operator because the language's grammar says so. There's also a unary + operator (that is converted to the +@ method) and the language's grammar allows Ruby to know which is which. The language definition says that operators are implemented as method calls and specifies which method each operator maps to.

    What you're asking is the same as asking how o.m a is a call to the m method on o with a as an argument. That's just how Ruby's syntax and semantics are defined.

    Operators are functions even in theoretical mathematics. The a + b notation is really just a convenient notation for +(a, b) (where +:R2R or a function from R×R to R, for example). I think you're reading too much into the notation and thinking that operators are something special, they're not, they're just function calls in computer languages and mathematics alike.

    In short, it works because that's how Ruby is defined to work.

    As far as

    could 3 be an method method called on '+' method ?

    is concerned, 3 is an argument or parameter to the + method on the Fixnum object 2.