From: Logan Capaldo Date: 2006-04-02T08:50:07+09:00 Subject: Re: Ruby way to sum digits On Apr 1, 2006, at 9:29 AM, James Edward Gray II wrote: > 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 > num_s = num.to_s (0...(num_s.length)).inject(0) { |s, i| s += (num_s[i] - ?0) } Just to increase confusion and to rely on the properties of ASCII