Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby overload + operator

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 
like image 862
Ravenous Avatar asked Jun 25 '26 21:06

Ravenous


1 Answers

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.

like image 50
Cthulhu Avatar answered Jun 28 '26 15:06

Cthulhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!