How to Convert a String to an Integer in Ruby?

In Ruby, you can either use the Kernel#Integer method or the String#to_i method to convert a string into an integer:

puts "50".to_i #=> 50
puts Integer("50") #=> 50

However, the Integer method raises an exception when the string is not strictly numeric, whereas the to_i method, comparatively, never raises an exception, but rather returns 0 if the leading characters are not numeric. To decide which one best suits your need, consider the following examples with comparisons between the two:

Case 1 — when a string starts with a number but has additional non-numeric characters:

puts "50 foo".to_i #=> 50

# Error: invalid value for Integer(): "50 foo" (ArgumentError)
Integer("50 foo")

Case 2 — when a string doesn't start with a number:

puts "foo 50".to_i #=> 0

# Error: invalid value for Integer(): "foo 50" (ArgumentError)
Integer("foo 50")

Case 3 — when a string doesn't have any numbers:

puts "foo bar".to_i #=> 0

# Error: invalid value for Integer(): "foo bar" (ArgumentError)
Integer("foo bar")

Case 4 — when a string contains a floating point number:

puts "50.123".to_i #=> 50

# Error: invalid value for Integer(): "50.123" (ArgumentError)
Integer("50.123")

Case 5 — when a string contains a binary number:

puts "0b100000000".to_i #=> 0
puts "0b100000000".to_i(2) #=> 256
puts "100000000".to_i(2) #=> 256

puts Integer("0b100000000") #=> 256
puts Integer("0b100000000", 2) #=> 256
puts Integer("100000000", 2) #=> 256

Case 6 — when a string contains an octal number:

puts "0400".to_i #=> 400
puts "0400".to_i(8) #=> 256
puts "400".to_i(8) #=> 256

puts Integer("0400") #=> 256
puts Integer("0400", 8) #=> 256
puts Integer("400", 8) #=> 256

Case 7 — when a string contains a hexadecimal number:

puts "0x100".to_i #=> 0
puts "0x100".to_i(16) #=> 256
puts "100".to_i(16) #=> 256

puts Integer("0x100") #=> 256
puts Integer("0x100", 16) #=> 256
puts Integer("100", 16) #=> 256

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.