Created
January 7, 2012 05:16
-
-
Save bitops/1573869 to your computer and use it in GitHub Desktop.
Digit sum in Ruby 1.9.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def digit_sum(n) | |
n.to_s.each_char.map {|c| c.to_i }.reduce(:+) | |
end |
what about this one:
n.to_s.chars.inject { |sum,n| sum = sum.to_i + n.to_i}
n.digits.inject(:+)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shorter and more understandable with: