Last Updated: February 25, 2016
·
269
· mbillard

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.