Stricter Conversions With Integer And Float
This is based on The Well Grounded Rubyist book, you should definitely buy it
As a ruby programmer you probably have experimented with converting strings to integers:
Well Ruby has some secrets under their slive with this conversion:
As you can see if your string has no reasonable integer equivalent (“hello”) ruby to_i
method will always return 0. Otherwise if your string starts with digit but isn’t made up entirely of digits (“123hello”), the nondigit parts are ignored and the conversion is perfomed only on the leading digits. The same thing happen with to_f
method:
Sweet huh? But what about if the conversion methods are too flexible for your purposes? What about if you want to avoid those kind of things? Well lucky for you, Ruby has a couple of stricter conversion techniques: Integer
and Float
So if you want to be strict about what gets converted and what gets rejected, Integer
and Float
can help you on :)