Home>

### i want to convert python3 code to ruby (total number of integer digits until it becomes 1 digit

I want to convert python3 code to ruby.

``````def digitSum (n):
# Determine number of digits
if len (str (n)) is 1:
return n
dst = sum (list (map (int, str (n))))
return digitSum (dst)

if __name__ == "__main__":
n = 12345
result = digitSum (n)
print (int (result)) # 15``````

The output will be 6.

I tried to write in ruby, but I didn't understand well.

``````gets;a = gets.split.map (&: to_i) .inject (: *)
b = a.to_s.chars.map (&: to_i) .sum
p b.to_s.chars.map (&: to_i) .sum if b.to_s.size>= 1``````

I don't know how to use if modifier or while modifier.
I don't even know about recursion ...

Reference
How to find the sum of integer digits | Python-suzu6
https://www.suzu6.net/posts/30/
"Repeat the calculation until the specified number of digits is reached.

"" "
Calculate the total value for each digit
Repeat until the number of digits reaches 1
"" "
def digitSum (n):

Judge the number of digits

if len (str (n)) is 1:
return n
dst = sum (list (map (int, str (n))))
return digitSum (dst)

ifname== "main":
n = 12345
result = digitSum (n)

print (int (result)) # 15 "