Reputation: 356
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
Upvotes: 3
Views: 1001
Reputation: 1372
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.
Upvotes: 6