Ruby Program to Find Sum of Digits
number.to_s.chars.map(&:to_i).sum.Examples
How to Think About It
Algorithm
Code
puts "Enter a number:" number = gets.chomp sum = number.chars.map(&:to_i).sum puts "Sum of digits: #{sum}"
Dry Run
Let's trace the input '123' through the code
Input number
number = '123'
Split into characters
number.chars = ['1', '2', '3']
Convert to integers
['1', '2', '3'].map(&:to_i) = [1, 2, 3]
Sum digits
[1, 2, 3].sum = 6
Print result
Output: 'Sum of digits: 6'
| Iteration | Digit (char) | Digit (int) | Running Sum |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 3 |
| 3 | 3 | 3 | 6 |
Why This Works
Step 1: Convert number to string
We convert the number to a string so we can look at each digit separately using to_s.
Step 2: Split string into characters
Splitting the string with chars gives us an array of digit characters.
Step 3: Convert characters to integers and sum
We convert each character back to an integer with map(&:to_i) and then add them all using sum.
Alternative Approaches
puts "Enter a number:" number = gets.to_i sum = 0 while number > 0 sum += number % 10 number /= 10 end puts "Sum of digits: #{sum}"
def sum_digits(n) return 0 if n == 0 n % 10 + sum_digits(n / 10) end puts "Enter a number:" number = gets.to_i puts "Sum of digits: #{sum_digits(number)}"
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each digit once, so time grows linearly with the number of digits, making it O(n).
Space Complexity
Converting the number to a string and then to an array of digits uses extra space proportional to the number of digits, so O(n).
Which Approach is Fastest?
The arithmetic method uses constant space O(1) and is generally faster for very large numbers, while the string method is simpler and more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String conversion and sum | O(n) | O(n) | Readability and simplicity |
| Arithmetic operators | O(n) | O(1) | Performance with large numbers |
| Recursion | O(n) | O(n) | Learning recursion, less efficient |
number.to_s.chars.map(&:to_i).sum for a clean and simple solution.