2.24. Converting Strings to Numbers (Decimal and Otherwise)

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")      # 123

When a string is not a valid number, however, their behaviors differ:

x = "junk".to_i         # silently returns 0
y = Integer("junk")     # error

to_i stops converting when it reaches a non-numeric character, but Integer raises an error:

x = "123junk".to_i      # 123
y = Integer("123junk")  # error

Both allow leading and trailing whitespace:

x = " 123 ".to_i ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.