Robert Klemme
11/4/2008 3:17:00 PM
2008/11/4 Daniel Vartanov <daniel.vartanov@gmail.com>:
> 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