In Ruby, it seems that a lot of coerce() help can be done by
def coerce(something)
[self, something]
end
that’s is, when
3 + rational
is needed, Fixnum 3 doesn’t know how to handle adding a Rational, so it asks Rational#coerce for help by calling rational.coerce(3), and this coerce instance method will tell the caller:
# I know how to handle rational + something, so I will return you the following:
[self, something]
# so that now you can invoke + on me, and I will deal with Fixnum to get an answer
So what if most operators can use this method, but not when it is (a – b) != (b – a) situation? Can coerce() know which operator it is, and just handle those special cases, while just using the simple [self, something] to handle all the other cases where (a op b) == (b op a) ? (op is the operator).
The point of
coerceis not to know what operation you are trying to perform. Its purpose is to bring the argument andselfto a common ground. Additionally, same operators can be commutative in certain classes, and not in other (Numeric#+andArray#+, for example), so your small commutativity-basedcoerceexploit really won’t pay off.Instead of pushing your
coerceto do what it’s not intended to, you should create a new class instead (such asScalarPoint, for example), and use it to interface scalar values with yourPoint:and
etc. (NB: code not tested)