Skip to content

Instantly share code, notes, and snippets.

@bitops
Created January 7, 2012 05:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitops/1573869 to your computer and use it in GitHub Desktop.
Save bitops/1573869 to your computer and use it in GitHub Desktop.
Digit sum in Ruby 1.9.2
def digit_sum(n)
n.to_s.each_char.map {|c| c.to_i }.reduce(:+)
end
@obfuscoder
Copy link

Shorter and more understandable with:

n.to_s.chars.map(&:to_i).reduce(:+)

@iamparnab
Copy link

what about this one:
n.to_s.chars.inject { |sum,n| sum = sum.to_i + n.to_i}

@bilalfayyaz93
Copy link

n.digits.inject(:+)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment