From: Robert Klemme Date: 2008-11-05T00:16:52+09:00 Subject: Re: Conditional overriding of operators 2008/11/4 Daniel Vartanov : > Thanks, guys! coercing mechanism is really useful. Due to multiplication > is commutative, I just swapped multiplier in coerce method, so even if > (2 * vector) is called, it calls vector.+(2) finally. > > def *(scalar) > Vector.new(x * scalar, y * scalar) > end > > def coerce(scalar) > [self, scalar] > end I am not sure whether this implementation adheres to the contract of #coerce. Normally you need to return the representative of the *other* instance first: irb(main):002:0> 1.coerce 2.0 => [2.0, 1.0] It may be ok in your case though. Note also, that you do no type checking in #* which you should do in order to properly react on values other than scalars. IMHO normally the logic should be "if the other instance is not of the same class as self invoke #coerce on it". > vector * 2 # vector.*(2) is called > 2 * vector # 2.*(vector), then vector.coerce(2), then vector.*(2) Kind regards robert -- remember.guy do |as, often| as.you_can - without end