In Ruby, a string should be converted to an integer in one of two ways:
If we use a normal string representation of an integer (e.g. “123”), both these would seem to act the same. For some string though, they act differently:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Using to_i is better in situations when you only care about the beginning of a string, don’t care about leading zeros, want to return 0 on invalid integers, and the number is represented in decimal (base 10) form. Integer is better in situations where you want to support decimal, binary, octal forms and you want to make sure that an exception is raised if the string passed is not a valid integer.
Similarly, if you are using to_f or Float, to_f will ignore the portion of the string which is no longer numeric (e.g. “3.03beer”.to_f # => 3.03) and return 0.0 while Float will raise an exception if the string has any portion that is not numeric (e.g. Float(“foo”) and Float(“3.03beer”) will raise exceptions). Unlike to_i and Integer, both to_f and Float will ignore leading zeros.