From: ara.t.howard@... Date: 2006-03-19T08:11:59+09:00 Subject: Re: can you enable coercion between types? On Sun, 19 Mar 2006, larry wrote: > I have a ruby class called Duration that represents a unit of time. > It's main attribute is a number that represents the duration in > seconds. > > If I try to save it to a DB using Rails, I get a "Duration can not be > coerced into Float" error. Is there a way to modify the definition of > Duration to enable automatic coercion into a float? (I'm thinking of > something like adding a "to_float" method to the class.) > > thanks in advance > larry 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 end p(40.0 + Duration::new(2.0)) p(40 + Duration::new(2)) harp:~ > ruby a.rb 42.0 42 hth. -a -- share your knowledge. it's a way to achieve immortality. - h.h. the 14th dali lama