In Ruby, can the coerce() method know what operator it is that requires the help to coerce?
Posted
by Jian Lin
on Stack Overflow
See other posts from Stack Overflow
or by Jian Lin
Published on 2010-05-11T02:07:38Z
Indexed on
2010/05/11
2:14 UTC
Read the original article
Hit count: 312
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).
© Stack Overflow or respective owner