From: Robert Klemme Date: 2004-09-17T23:49:46+09:00 Subject: Re: Automatic class conversion / function overloading "Markus" schrieb im Newsbeitrag news:1095431743.19139.114.camel@lapdog.reality.com... > On Fri, 2004-09-17 at 06:44, Tore Halvorsen wrote: > > > So the ruby way here would be: > > > > class Rational > > attr_reader :u, :d > > def *(o) > > case other > > when Rational > > other = o > > when Fixnum > > other = Rational.new(o, 1) > > end > > Rational.new(self.u * other.u, self.d * other.d) > > end > > end > > Perhaps. But (as others have noted) there isn't a single unique ruby > way. My ruby way would be more like > > > class Rational > attr_reader :u, :d > def *(other) > other = Rational.new(other, 1) if other.is_a? Fixnum > Rational.new(self.u * other.u, self.d * other.d) > end > end > > > But as you can see, I even use the old salient-structure > indentation rules. Depending on the situation, I might also write: > > > class Fixnum > def to_rational > Rational.new(self,1) > end > end > > class Rational > attr_reader :u, :d > def *(other) > other = other.to_rational unless other.is_a? Rational > Rational.new(self.u * other.u, self.d * other.d) > end > end > > Which would permit types other than Fixnum, provided they implemented > to_rational. Taking this to its logical conclusion I would surely then > rewrite it as: > > class Fixnum > def to_rational > Rational.new(self,1) > end > end > > class Rational > attr_reader :u, :d > def to_rational > self > end > def *(other) > other = other.to_rational > Rational.new(self.u * other.u, self.d * other.d) > end > end > > ..which eliminates all class testing and is fairly easily extensible. > But of course others might have different solutions. > > -- MarkusQ Btw: you know that there are classes Rational, Complex etc. already, do you? robert