Forum: Ruby Why does mathn kill this method?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D7908f05c89e965f6bc5308ad6f41256?d=identicon&s=25 Siep Korteling (steenslag)
on 2009-04-01 00:46
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?
D7463bd611f227cfb2ef4da4a978a203?d=identicon&s=25 Christopher Dicely (Guest)
on 2009-04-01 01:08
(Received via mailing list)
On Tue, Mar 31, 2009 at 3:46 PM, Siep Korteling <s.korteling@gmail.com>
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
Ae16cb4f6d78e485b04ce1e821592ae5?d=identicon&s=25 Martin DeMello (Guest)
on 2009-04-01 01:09
(Received via mailing list)
On Wed, Apr 1, 2009 at 4:16 AM, Siep Korteling <s.korteling@gmail.com>
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
D7908f05c89e965f6bc5308ad6f41256?d=identicon&s=25 Siep Korteling (steenslag)
on 2009-04-01 01:16
Martin DeMello wrote:
> On Wed, Apr 1, 2009 at 4:16 AM, Siep Korteling <s.korteling@gmail.com>
> 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
This topic is locked and can not be replied to.