I'm trying to solve a Digital Root problem using Recursion. It seems to work for the first time around but not for the consecutive times. Here's what I want it to do:
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
Here's what I got:
def digital_root(n)
arr = n.to_s.split("")
arr.size > 1 ? arr[0].to_i + digital_root(arr[1..-1].join).to_i : arr.join.to_i
end
Let me know how to make it work regardless of how many layers I need. Thanks in advance.