Ruby How to Convert Integer to String Easily
In Ruby, you can convert an integer to a string by calling
to_s on the integer, like 123.to_s.Examples
Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
How to Think About It
To convert an integer to a string in Ruby, think of it as changing the number into text form so you can use it where words are needed. Ruby provides a simple way by calling
to_s on the number, which turns it into its string equivalent.Algorithm
1
Take the integer value as input.2
Call the <code>to_s</code> method on the integer.3
Return the resulting string.Code
ruby
number = 123
string_version = number.to_s
puts string_versionOutput
123
Dry Run
Let's trace converting the integer 123 to a string.
1
Start with integer
number = 123
2
Convert to string
string_version = number.to_s # string_version is now "123"
3
Print the string
puts string_version # outputs 123
| Step | Value |
|---|---|
| Initial integer | 123 |
| After to_s | "123" |
| Output | 123 |
Why This Works
Step 1: Using to_s method
The to_s method is built into Ruby for integers and converts the number into its string form.
Step 2: Result is a string
After calling to_s, the integer becomes a string that can be used like any text.
Alternative Approaches
String() method
ruby
number = 123
string_version = String(number)
puts string_versionThis also converts the integer to a string but is less commonly used than <code>to_s</code>.
Complexity: O(1) time, O(n) space
Time Complexity
Converting an integer to a string takes constant time because it just formats the number.
Space Complexity
The space depends on the number of digits since the string stores each digit as a character.
Which Approach is Fastest?
Both to_s and String() have similar performance; to_s is preferred for readability.
| Approach | Time | Space | Best For |
|---|---|---|---|
| to_s method | O(1) | O(n) | Simple and readable conversion |
| String() method | O(1) | O(n) | Alternative but less common |
Use
to_s to quickly convert any integer to a string in Ruby.Forgetting to call
to_s and trying to use the integer directly as a string.