From: Robert Klemme Date: 2004-05-02T20:53:59+09:00 Subject: Re: Commutativity of '*' "Stephan K�mper" schrieb im Newsbeitrag news:c72lo9$hi3jp$1@ID-96582.news.uni-berlin.de... > Hi all, > > say I have a new class Foo which provides * as a multiplicative method. > Now, given the following lines: > > def some_operation_using( lft, rgt ) > return "#{lft} times #{rgt}" > end > > class Foo > > def *( other ) > # do something > res = some_operation_using( other, self ) > return res > end > > def to_s > return "a Foo thingy." > end > > end > > # That given, the following lines will work > > f = Foo.new > puts f * 42.0 > > # But this won't. Instead I get: > # .../lm.rb:25:in `*': Foo can't be coerced into Float (TypeError) > # from .../lm.rb:25 > puts 42.0 * f > > What would be a (or even the) Ruby Way to get the last line to work? > Some method to coerce a Foo into a Float? Or some hacking of Float > itself? Like adding that, for example: > > class Float > alias old_mult * > def *( other ) > if other.class == Foo > return other * self > else > return self.old_mult( other ) > end > end > end > > That doesn't seem to be terribly elegant, I think. > > Any other way? You want coerce. See my posting in thread "coerce(), what protocol to implement it" from 30 Apr. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/98791 Kind regards robert