Really stumped here. def sum_digits(n) sum = 0 while n>0 sum += n % 10 n /= 10 end sum end STDOUT.sync=true puts sum_digits(12) #=> 3 require 'mathn' puts sum_digits(12) # hangs What am I doing wrong?

on 2009-04-01 02:46

on 2009-04-01 03:08

On Tue, Mar 31, 2009 at 3:46 PM, Siep K. <removed_email_address@domain.invalid> wrote: > > STDOUT.sync=true > > puts sum_digits(12) #=> 3 > > require 'mathn' > puts sum_digits(12) # hangs > > > What am I doing wrong? This should illustrate the problem: irb(main):001:0> require 'mathn' => true irb(main):002:0> n = 10 => 10 irb(main):003:0> n /= 10 => 1 irb(main):004:0> n /= 10 => 1/10 irb(main):005:0> n /= 10 => 1/100 The solution: def sum_digits(n) sum = 0 while n>0 sum += n % 10 n = n.div 10 end sum end

on 2009-04-01 03:09

On Wed, Apr 1, 2009 at 4:16 AM, Siep K. <removed_email_address@domain.invalid> wrote: > > STDOUT.sync=true > > puts sum_digits(12) #=> 3 > > require 'mathn' > puts sum_digits(12) # hangs n /= 10 just keeps making n into a smaller and smaller rational. it never reaches 0 martin

on 2009-04-01 03:16

Martin DeMello wrote: > On Wed, Apr 1, 2009 at 4:16 AM, Siep K. <removed_email_address@domain.invalid> > wrote: >> >> STDOUT.sync=true >> >> puts sum_digits(12) #=> 3 >> >> require 'mathn' >> puts sum_digits(12) # hangs > > n /= 10 just keeps making n into a smaller and smaller rational. it > never reaches 0 > > martin Yes, that's clear. Thanks for the help (real fast), Christopher and Martin. Siep