Hi, Robert.
> 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]
Swapping is the main point here, we exploit commutativity of
multiplication. If Numeric can be *converted back* to your type, you can
use this approach (actually you mentioned it in one of threads

):
def coerce(x) [self.class.new( x ), self]; end
But Numeric cannot be converted back to Vector. Just look what people do
in case of subtraction, which is not commutative:
http://groups.google.com/group/ruby-...288902532dcc6c
(note, he uses swapping too)
> Note also, that you do no type checking in #* which you should do in order to
> properly react on values other than scalars.
I think you a right here, thanks for comment. I relied on the Vector.*
method, where an exception will be raised if numerical components of
vector is multiplied by something else than Numeric. But such exception
is not descriptive enough, so I decided to include such checking:
def coerce(scalar)
if scalar.is_a?(Numeric)
[self, scalar]
else
raise ArgumentError, "Vector: cannot coerce #{scalar.inspect}"
end
end
--
Posted via
http://www.ruby-forum.com/.