From: Sylvester Keil Date: 2011-12-05T20:17:30+09:00 Subject: Re: Stupid question 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. 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? > >>> x = 2011 > => 2011 >>> q = 0 > => 0 >>> a = x > => 2011 >>> while a>0;a,b=a.divmod 10;q+=b;end > => nil >>> q > => 4 > > Granted, this is not too short - but it works without creating a > String instance. > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ >