Fix for rational.rb (accepting Rationals as num/den)

S

Stefan Rusterholz

Hi, Rational currently doesn't accept Rationals as
Numerator/Denominator. I wrote a patch for it and look for feedback.
Thanks.

def Rational(a, b = 1)
Rational.reduce(*Rational.normalize(a,b))
end

class Rational < Numeric
# normalizes numerator/denominator to non-rationals
def Rational.normalize(num,den)
if a.kind_of?(Rational) then
if b == 1 then
return [a.nominator, a.denominator]
elsif b.kind_of?(Rational) then
return [a.numerator*b.denominator, a.denominator*b.numerator]
else
return [a.numerator, a.denominator*b]
end
elsif b.kind_of?(Rational) then
if a == 1 then
return [b.denominator, b.nominator]
else
return [a*b.denominator, b.numerator]
end
else
return [a,b]
end
end

def Rational.new!(num, den = 1)
new(*Rational.normalize(a,b))
end
end
 
S

Stefan Rusterholz

Whoops, that was the old code snippet...

def Rational(a, b = 1)
Rational.reduce(*Rational.normalize(a,b))
end

class Rational < Numeric
# normalizes numerator/denominator to non-rationals
def Rational.normalize(a,b)
if a.kind_of?(Rational) then
if b == 1 then
return [a.nominator, a.denominator]
elsif b.kind_of?(Rational) then
return [a.numerator*b.denominator, a.denominator*b.numerator]
else
return [a.numerator, a.denominator*b]
end
elsif b.kind_of?(Rational) then
if a == 1 then
return [b.denominator, b.nominator]
else
return [a*b.denominator, b.numerator]
end
else
return [a,b]
end
end

def Rational.new!(num, den = 1)
new(*Rational.normalize(num,den))
end
end

Should work a bit better ;-)
 
B

bbiker

Stefan said:
Whoops, that was the old code snippet...

def Rational(a, b = 1)
Rational.reduce(*Rational.normalize(a,b))
end

class Rational < Numeric
# normalizes numerator/denominator to non-rationals
def Rational.normalize(a,b)
if a.kind_of?(Rational) then
if b == 1 then
return [a.nominator, a.denominator]
elsif b.kind_of?(Rational) then
return [a.numerator*b.denominator, a.denominator*b.numerator]
else
return [a.numerator, a.denominator*b]
end
elsif b.kind_of?(Rational) then
if a == 1 then
return [b.denominator, b.nominator]
else
return [a*b.denominator, b.numerator]
end
else
return [a,b]
end
end

def Rational.new!(num, den = 1)
new(*Rational.normalize(num,den))
end
end

Should work a bit better ;-)

Tested the code and it appears to do it correctly

add /substact rationals
raise rational to rational
add/substract rational and integer
add/substract rational and float


About the only thing I tried but could not do would be rational to mix
number

Rational(11,7).to_mix => "11 4/7"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,145
Latest member
web3PRAgeency
Top