Markus
3/19/2006 5:20:00 AM
On Sat, 2006-03-18 at 17:11, ara.t.howard@noaa.gov wrote:
> try this:
>
> harp:~ > cat a.rb
> class Duration
> def initialize seconds
> @seconds = seconds
> end
> def coerce other
> if other.class == @seconds.class
> [@seconds, other]
> else
> [Float(@seconds), Float(other)]
> end
> end
There's a gottcha here. Coerce is used to implement double dispatch and
so needs to return the coerced values in the opposite order (see Pick
Axe)--(other,self), not (self,other).
The way you wrote it works fine for addition & multiplication, but
you'll pull your hair out the first time you try to subtract or divide.
--MarkusQ
P.S. And I think (as Tom noted) that "to_f" was the answer to the
original question.