Fixnum#+
is just a method. Simplified it works like this:
class Fixnum
def +(other)
if Fixnum === other
# normal operation
else
n1, n2= other.coerce(self)
return n1+n2
end
end
end
coerce
is used for automatic numerical type conversion. This is used for example if you do 42 + 3.141
. A string in ruby cannot automaticly be converted into numerical values. You could enhance the String
class to be able to do this. You just need to do
class String
def coerce(other)
coerced= case other
when Integer
self.to_i
when
self.to_f
end
return coerced, other
end
end
Now you can do
23 + "42" # => 65
0.859 - "4" # => 3.141
This does not work the other way arround. coerce
is only for numerical values "23" + 42
won't work. String#+
will not use coerce.
The simplified +
is done in Fixnum
and not in Integer
on purpose. Fixnum
and Bignum
have their separate methods, because they work internally very different.