Safe integer parsing in Ruby Safe integer parsing in Ruby ruby ruby

Safe integer parsing in Ruby


Ruby has this functionality built in:

Integer('1001')                                    # => 1001  Integer('1001 nights')  # ArgumentError: invalid value for Integer: "1001 nights"  

As noted in answer by Joseph Pecoraro, you might want to watch for strings that are valid non-decimal numbers, such as those starting with 0x for hex and 0b for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.

Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:

Integer('23')                                     # => 23Integer('0x23')                                   # => 35Integer('023')                                    # => 19Integer('0x23', 10)# => #<ArgumentError: invalid value for Integer: "0x23">Integer('023', 10)                                # => 23


Also be aware of the affects that the current accepted solution may have on parsing hex, octal, and binary numbers:

>> Integer('0x15')# => 21  >> Integer('0b10')# => 2  >> Integer('077')# => 63

In Ruby numbers that start with 0x or 0X are hex, 0b or 0B are binary, and just 0 are octal. If this is not the desired behavior you may want to combine that with some of the other solutions that check if the string matches a pattern first. Like the /\d+/ regular expressions, etc.