On Mon, Dec 5, 2011 at 12:17 PM, Sylvester Keil
<sylvester.keil / gmail.com> wrote:
>
> On Dec 5, 2011, at 11:38 AM, Robert Klemme wrote:
>
>> On Mon, Dec 5, 2011 at 10:03 AM, James Gallagher
>> <lollyproductions / mac.com> wrote:
>>> Thank you everyone for Helping me out. =A0:-)
>>
>> If I am not mistaken, everybody in this thread resorted to using a
>> string conversion. =A0Why 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 =3D 2011
> n.size.pred.downto(0).reduce(0) { |sum, a| sum +=3D (n.abs / 10 ** a) % 1=
0 }
>
> The while loop is more straightforward though. Perhaps we could combine t=
he 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 =3D 90000
=3D> 90000
>> n.size.pred.downto(0).reduce(0) { |sum, a| sum +=3D (n.abs / 10 ** a) % =
10 }
=3D> 0
>> n.size
=3D> 4

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/