0
0
RubyHow-ToBeginner · 2 min read

Ruby How to Convert String to Integer with Examples

In Ruby, you can convert a string to an integer using the to_i method like this: "123".to_i which returns the integer 123.
📋

Examples

Input"123"
Output123
Input"007"
Output7
Input"abc"
Output0
🧠

How to Think About It

To convert a string to an integer in Ruby, think about using a built-in method that reads the string characters and turns them into a number. Ruby's to_i method does this by scanning the string from the start and converting any leading digits into an integer, ignoring non-digit characters after the number or returning zero if no digits are found.
📐

Algorithm

1
Take the input string.
2
Use the built-in method to convert the string to an integer.
3
Return the integer result.
💻

Code

ruby
str = "123"
num = str.to_i
puts num
Output
123
🔍

Dry Run

Let's trace converting the string "123" to an integer using to_i.

1

Start with string

str = "123"

2

Convert string to integer

num = str.to_i # num becomes 123

3

Print the integer

puts num # outputs 123

StepStringInteger Result
1"123"N/A
2"123"123
3N/A123
💡

Why This Works

Step 1: Using to_i method

The to_i method reads the string from left to right and converts any leading digits into an integer.

Step 2: Non-digit characters

If the string starts with non-digit characters, to_i returns 0 because it cannot find a number at the start.

Step 3: Ignoring trailing characters

Any characters after the initial digits are ignored during conversion.

🔄

Alternative Approaches

Integer() method
ruby
str = "123"
num = Integer(str)
puts num
Raises an error if the string is not a valid integer, unlike to_i which returns 0.
Using Kernel#Integer with rescue
ruby
str = "abc"
num = Integer(str) rescue 0
puts num
Handles invalid strings by rescuing the error and returning 0.

Complexity: O(n) time, O(1) space

Time Complexity

The to_i method scans the string once from left to right, so it takes linear time proportional to the string length.

Space Complexity

Conversion uses constant extra space since it only stores the resulting integer.

Which Approach is Fastest?

to_i is fast and safe for general use. Integer() is slightly slower due to error checking but useful when invalid input should raise errors.

ApproachTimeSpaceBest For
to_iO(n)O(1)Safe conversion, returns 0 on invalid input
Integer()O(n)O(1)Strict conversion, raises error on invalid input
Integer() with rescueO(n)O(1)Strict conversion with error handling
💡
Use to_i for safe conversion that returns 0 on invalid strings, and Integer() if you want an error on bad input.
⚠️
Expecting to_i to raise an error on invalid strings, but it returns 0 instead.