Number Parsing in Ruby
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Ruby.
When you run this program, you’ll see:
In Ruby, number parsing is generally more straightforward than in some other languages. The to_f
and to_i
methods are commonly used for parsing floating-point and integer values, respectively.
Ruby doesn’t have separate unsigned integer types, so all integers are signed. The to_i
method can be used for parsing both signed and unsigned integers.
For hex numbers, you can use to_i(16)
to specify base 16.
Ruby’s number parsing is more forgiving than some languages, often returning 0 for invalid input rather than raising an error. However, if you need stricter parsing, you can use Integer()
and Float()
methods, which will raise an ArgumentError
for invalid input.
Next, we’ll look at another common parsing task: URLs.