DEV Community

Discussion on: Solving the Digital Root Algorithm using JavaScript

Collapse
 
kdraypole profile image
Kobe Raypole

Very cool! I'm a Ruby enthusiast so I tried it out in that.

Your Iterative strategy was great but I think using recursion could help reduce some of the complexity and make for some cleaner code.

def d_root(num)
  return num if num < 10

  d_root(num.to_s.split('').reduce(0) {|acc, digit| acc + digit.to_i}) 
end

Ruby gives us some great helpers for integers so we can simplify this even more.

def d_root(num)
  return num if num < 10

  d_root(num.digits.sum) 
end

Nice and simple!