3

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 
3
  • 3
    2 + 2 is not a good example to test the difference between + and * Commented Mar 10, 2016 at 0:17
  • I was only trying to show that I wanted to change the behaviour of +. I was trying to figure out how to land in that +(a,b) function. All I was attempting to get was anything besides 4 from 2 + 2. Commented Mar 10, 2016 at 0:25
  • Just curious: what made you think + 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 is self, 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. Commented Mar 10, 2016 at 9:07

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't plan on actually using this for anything. I just didn't understand that it's resolved based on first class. I just arbitrarily picked + and *. Once I saw that 2 + 2 didn't equal 4 I knew I succeeded, and I threw away the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.