From: Paul Battley Date: 2006-10-06T07:48:41+09:00 Subject: Re: Why can't Ruby automatically cast variables? On 30/09/06, Joe Ruby MUDCRAP-CE wrote: > One thing that annoys me about Ruby is that casting variables is > required: > > i = 5 > a = 'logan' > > puts a + i.to_s > > Or > > a='2' > b=3 > > puts a.to_i + b > > Why can't (or can?) Ruby just handle 'puts a + i' or 'puts a+b'? I don't suggest you actually use this, but: class String def coerce(lhs) [lhs, self.to_i] end alias_method :old_plus, :+ def +(rhs) if rhs.is_a?(Numeric) return rhs + self else return old_plus(rhs) end end end 1 + '1' #=> 2 '2' + 2 #=> 4 'foo' + 'bar' #=> "foobar" Paul.