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.

# Ruby provides built-in methods for number parsing

# With `to_f`, we can parse floating-point numbers
f = "1.234".to_f
puts f

# For integer parsing, we can use `to_i`
i = "123".to_i
puts i

# Ruby automatically recognizes hex-formatted numbers
d = "0x1c8".to_i(16)
puts d

# For unsigned integers, Ruby doesn't have a specific type, 
# but we can use `to_i` and ensure it's positive
u = "789".to_i
puts u

# Ruby's `to_i` is similar to Go's `Atoi` for basic base-10 parsing
k = "135".to_i
puts k

# Ruby's number parsing is more forgiving, but we can check for errors
begin
  Integer("wat")
rescue ArgumentError => e
  puts e.message
end

When you run this program, you’ll see:

$ ruby number_parsing.rb
1.234
123
456
789
135
invalid value for Integer(): "wat"

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.