*(rhs)
click to toggle source
def *(rhs)
if rhs.is_a? Rational
Rational(numerator * rhs.numerator, denominator * rhs.denominator)
elsif rhs.is_a? Integer
Rational(numerator * rhs, denominator)
elsif rhs.is_a? Numeric
numerator * rhs / denominator
end
end
+(rhs)
click to toggle source
def +(rhs)
if rhs.is_a? Rational
Rational(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator)
elsif rhs.is_a? Integer
Rational(numerator + rhs * denominator, denominator)
elsif rhs.is_a? Numeric
(numerator + rhs * denominator) / denominator
end
end
-(rhs)
click to toggle source
def -(rhs)
if rhs.is_a? Rational
Rational(numerator * rhs.denominator - rhs.numerator * denominator, denominator * rhs.denominator)
elsif rhs.is_a? Integer
Rational(numerator - rhs * denominator, denominator)
elsif rhs.is_a? Numeric
(numerator - rhs * denominator) / denominator
end
end
/(rhs)
click to toggle source
def /(rhs)
if rhs.is_a? Rational
Rational(numerator * rhs.denominator, denominator * rhs.numerator)
elsif rhs.is_a? Integer
Rational(numerator, denominator * rhs)
elsif rhs.is_a? Numeric
numerator / rhs / denominator
end
end
<=>(rhs)
click to toggle source
def <=>(rhs)
if rhs.is_a?(Integral)
return numerator <=> rhs if denominator == 1
rhs = Rational(rhs)
end
case rhs
when Rational
(numerator * rhs.denominator - denominator * rhs.numerator) <=> 0
when Numeric
(rhs <=> self)&.-@
else
nil
end
end
==(rhs)
click to toggle source
def ==(rhs)
return true if self.equal?(rhs)
if rhs.is_a?(Integral) && denominator == 1
return numerator == rhs
end
if rhs.is_a?(Rational)
numerator * rhs.denominator == denominator * rhs.numerator
else
rhs == self
end
end
inspect()
click to toggle source
def inspect
"(#{to_s})"
end
to_s()
click to toggle source
def to_s
"#{numerator}/#{denominator}"
end