Ruby Language Converting a String to Integer


Example

You can use the Integer method to convert a String to an Integer:

Integer("123")      # => 123
Integer("0xFF")     # => 255
Integer("0b100")    # => 4
Integer("0555")     # => 365

You can also pass a base parameter to the Integer method to convert numbers from a certain base

Integer('10', 5)    # => 5
Integer('74', 8)    # => 60
Integer('NUM', 36)  # => 30910

Note that the method raises an ArgumentError if the parameter cannot be converted:

Integer("hello")
# raises ArgumentError: invalid value for Integer(): "hello"
Integer("23-hello")
# raises ArgumentError: invalid value for Integer(): "23-hello"

You can also use the String#to_i method. However, this method is slightly more permissive and has a different behavior than Integer:

"23".to_i         # => 23
"23-hello".to_i   # => 23
"hello".to_i      # => 0

String#to_i accepts an argument, the base to interpret the number as:

"10".to_i(2) # => 2
"10".to_i(3) # => 3
"A".to_i(16) # => 10