2

I have a specific class C and I would like to overload some math operators.

I already overloaded +, i, *, and / so that I can do things like

a = C.new
b = C.new
a + b
a + 2
a + 2.0

To treat the last three cases, I am systematically testing for the type of the operand: is it C, Fixnum or Float, other possibilities are rejected. My first question is: is it the right way to do that?

Next I also want to be able to do

2.0 + A

How should I do it? Should I provide a conversion of some sort? Can these two problems be solved by the same method?

4
  • 3
    You can't do operator overloading in Ruby, only redefine the methods that the operators call (+, -, *, /, <, >, ...), if the operator calls a method. But there is no way to overload = in ruby. Commented Jun 20, 2012 at 0:03
  • possible duplicate of Why Does Ruby Only Permit Certain Operator Overloading Commented Jun 20, 2012 at 0:37
  • @the Tin Man : I don't how this could possibly be a duplicate of that question ... Commented Jun 20, 2012 at 1:57
  • @Tass: OK, so this is not overloading of the operators but of the methods. Commented Jun 20, 2012 at 1:57

1 Answer 1

4

I believe the answer to "ruby operator overloading question" addresses both your points by using is_a? and coerce.

With regards to your first point. The normal approach in Ruby is to use respond_to? where possible, rather than checking for type. If for some reason you specifically need to check for type, then using is_a? is the correct way.

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

1 Comment

Thanks, I didn't know about coerce.

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.