From: Robert Klemme Date: 2011-12-05T21:11:36+09:00 Subject: Re: Stupid question On Mon, Dec 5, 2011 at 12:17 PM, Sylvester Keil wrote: > > On Dec 5, 2011, at 11:38 AM, Robert Klemme wrote: > >> On Mon, Dec 5, 2011 at 10:03 AM, James Gallagher >> wrote: >>> Thank you everyone for Helping me out.  :-) >> >> If I am not mistaken, everybody in this thread resorted to using a >> string conversion.  Why does nobody want to calculate this >> numerically? > > I posted a similar version to yours which uses an iterator. Oh, I'm sorry I overlooked that one. > n = 2011 > n.size.pred.downto(0).reduce(0) { |sum, a| sum += (n.abs / 10 ** a) % 10 } > > The while loop is more straightforward though. Perhaps we could combine the two? I'm afraid your solution with Fixnum#size works only accidentally because it returns the byte size of the number which coindicentally is also the number of digits. It fails for other values: >> n = 90000 => 90000 >> n.size.pred.downto(0).reduce(0) { |sum, a| sum += (n.abs / 10 ** a) % 10 } => 0 >> n.size => 4 Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/