# Why does mathn kill this method?

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 Tue, Mar 31, 2009 at 3:46 PM, Siep K. [email protected]
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 Wed, Apr 1, 2009 at 4:16 AM, Siep K. [email protected]
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

Martin DeMello wrote:

On Wed, Apr 1, 2009 at 4:16 AM, Siep K. [email protected]
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.