Someone on the ruby-talk mailing list asked why you can't add strings and numbers without conversion as in Perl and PHP. Now, behaving like PHP is rarely a good thing, but Ruby can be made to do it in this case:
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
You can now add a string to a number:
1 + '1' #=> 2
Or a number to a string:
'2' + 2 #=> 4
Or, indeed, a string to a string as usual:
'foo' + 'bar' #=> "foobar"
I have expanded it to handle
'1' + '2' and
'4' - '3'. Here’s the file.