Something to be aware of when dealing with Ruby that the core docs don’t really document clearly enough: explicit vs. implicit conversions.
Ruby provides functions like to_i
and to_int
that at first blush seem to do exactly the same thing. Yet, try to do something like “42”.to_i and you get back the natural-seeming 42 as an Integer object, but “42”.to_int gives you a NoMethodError: undefined method `to_int'
. Why is that!?
Well, to_i
is an explicit conversion method. String
defines this as a helper method to allow you to convert String
s to Integer
s easily. However to_int
is an implicit conversion method and is only defined for objects that can always be treated as though they were an Integer
class. Therefore, String
does not define to_int
because not all strings can be treated as integers. However, Float
does define both to_i
and to_int
because in both cases it makes sense to be able to treat a Float
like ann Integer
.
There are lots of methods like this in Ruby (e.g. to_ary
(implicit) vs. to_a
(explicit)). Know how to use them and apply them to your classes as appropriate.
PS: Thanks go to Avdi Grimm and his Exceptional Ruby talk for pointing this out to me. Most enlightening! He also has more on this in his new book Confident Ruby – I bought it, think it’s well worth the $25 he’s asking in the beta version. ;]