Reputation: 8288
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?
Upvotes: 2
Views: 3889
Reputation: 2438
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.
Upvotes: 4