0
0
RubyProgramBeginner · 2 min read

Ruby Program for Sum of Digits Using Recursion

You can find the sum of digits of a number in Ruby using recursion by defining a method like def sum_of_digits(n); return n if n < 10; n % 10 + sum_of_digits(n / 10); end.
📋

Examples

Input5
Output5
Input1234
Output10
Input0
Output0
🧠

How to Think About It

To find the sum of digits using recursion, think of breaking the number into its last digit and the rest. Use the % operator to get the last digit and / to remove it. Then add the last digit to the sum of digits of the remaining number. Stop when the number is less than 10 because then it is a single digit.
📐

Algorithm

1
Check if the number is less than 10; if yes, return the number itself.
2
Find the last digit of the number using modulus 10.
3
Call the function recursively with the number divided by 10 (removing the last digit).
4
Add the last digit to the result of the recursive call.
5
Return the sum.
💻

Code

ruby
def sum_of_digits(n)
  return n if n < 10
  n % 10 + sum_of_digits(n / 10)
end

puts sum_of_digits(1234)
Output
10
🔍

Dry Run

Let's trace sum_of_digits(1234) through the code

1

Initial call

n = 1234, n >= 10, so calculate 1234 % 10 = 4 and call sum_of_digits(1234 / 10 = 123)

2

Second call

n = 123, n >= 10, calculate 123 % 10 = 3 and call sum_of_digits(123 / 10 = 12)

3

Third call

n = 12, n >= 10, calculate 12 % 10 = 2 and call sum_of_digits(12 / 10 = 1)

4

Base case

n = 1, n < 10, return 1

5

Return and sum up

Return 1 to previous call, sum 2 + 1 = 3, then 3 + 3 = 6, then 4 + 6 = 10

CallnLast Digit (n % 10)Remaining Number (n / 10)Return Value
1123441234 + sum_of_digits(123)
21233123 + sum_of_digits(12)
312212 + sum_of_digits(1)
41101
💡

Why This Works

Step 1: Base case stops recursion

When the number is less than 10, return n stops the recursion because a single digit's sum is itself.

Step 2: Extract last digit

Using n % 10 gets the last digit of the number to add to the sum.

Step 3: Recursive call reduces problem size

Calling sum_of_digits(n / 10) removes the last digit and repeats the process on the smaller number.

Step 4: Sum builds up on return

Each recursive call returns the sum of digits so far, adding the last digit until the full sum is computed.

🔄

Alternative Approaches

Iterative approach
ruby
def sum_of_digits_iterative(n)
  sum = 0
  while n > 0
    sum += n % 10
    n /= 10
  end
  sum
end

puts sum_of_digits_iterative(1234)
Uses a loop instead of recursion, which can be easier to understand for beginners and avoids stack overflow for very large numbers.
Convert to string and sum digits
ruby
def sum_of_digits_string(n)
  n.to_s.chars.map(&:to_i).sum
end

puts sum_of_digits_string(1234)
Converts the number to a string, then sums digits. Simple but less efficient for very large numbers.

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

Time Complexity

The function processes one digit per recursive call, so the number of calls is proportional to the number of digits, which is log base 10 of n.

Space Complexity

Each recursive call adds a layer to the call stack, so space used is proportional to the number of digits, O(log n).

Which Approach is Fastest?

The iterative approach uses constant space O(1) and is generally faster due to no recursion overhead, but recursion is elegant and easy to understand.

ApproachTimeSpaceBest For
RecursiveO(log n)O(log n)Learning recursion and elegant code
IterativeO(log n)O(1)Performance and large inputs
String conversionO(log n)O(log n)Simple code for small inputs
💡
Use the base case to stop recursion when the number is a single digit.
⚠️
Forgetting to reduce the number in the recursive call causes infinite recursion.