From: James Edward Gray II Date: 2006-04-01T23:29:43+09:00 Subject: Re: Ruby way to sum digits On Apr 1, 2006, at 7:22 AM, Marcus Lunzenauer wrote: > Hello! > > To sum the digits of an Integer I have got > > class Integer > def sum_digits() > sum = 0 > n = self > begin sum += n % 10; n /= 10 end while n > 0 > sum > end > end > > > Is there a more Ruby Way to do this? The above method smells of > Java, doesn't it? Here is what I thought of when reading this: >> class Integer >> def sum_digits >> to_s.split("").inject(0) { |sum, n| sum + n.to_i } >> end >> end => nil >> 1234.sum_digits => 10 Hope that helps. James Edward Gray II