October 2006
Intermediate to advanced
888 pages
16h 55m
English
Basically there are two ways to convert strings to numbers: the Kernel method Integer and Float and the to_i and to_f methods of String. (Capitalized method names such as Integer are usually reserved for special data conversion functions like this.)
The simple case is trivial, and these are equivalent:
x = "123".to_i # 123
y = Integer("123") # 123When a string is not a valid number, however, their behaviors differ:
x = "junk".to_i # silently returns 0
y = Integer("junk") # errorto_i stops converting when it reaches a non-numeric character, but Integer raises an error:
x = "123junk".to_i # 123
y = Integer("123junk") # errorBoth allow leading and trailing whitespace:
x = " 123 ".to_i ...
Read now
Unlock full access