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

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.numeratorb.denominator, a.denominatorb.numerator]
else
return [a.numerator, a.denominatorb]
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

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.numeratorb.denominator, a.denominatorb.numerator]
else
return [a.numerator, a.denominatorb]
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 :wink:

Stefan R. wrote:

  	if b == 1 then
  		return [a*b.denominator, b.numerator]

Should work a bit better :wink:


Posted via http://www.ruby-forum.com/.

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”

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs