Get the sum of all digits in a number
18.to_s.chars.map(&:to_i).reduce(:+) # => 9
123456789.to_s.chars.map(&:to_i).reduce(:+) # => 45
It transforms the number into a string, splits it into digits, transforms each into an integer and adds them all together.
Works with numbers of any length.
Written by Michel Billard
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#