What is the right way to overload operators in ruby? What do I need to do to redefine how + works? This function isn't being called when the + operator is used.
def +(a,b)
return a * b
end
p 2 + 2
Overloaded operator is resolved based on the class of the first operand, so if you wanted to overload the addition of simple integers, something like that should work:
class Fixnum
def +(other)
return self * other
end
end
I do not recommend you to actually do this, btw.
2 + 2is not a good example to test the difference between+and*+has two parameters? To me, it seems blindingly obvious that it should have only one: it's a binary operator, after all, and binary operators have two operands, which is why they are called "binary" operators. The first operand isself, obviously, since Ruby is an OO language, and so there can only be one other argument. Plus, of course, the documentation or+only ever lists a single argument.