1 class Rational < Numeric
7 "#{numerator}/#{denominator}"
12 Rational(numerator * rhs.numerator, denominator * rhs.denominator)
13 elsif rhs.is_a? Integer
14 Rational(numerator * rhs, denominator)
15 elsif rhs.is_a? Numeric
16 numerator * rhs / denominator
22 Rational(numerator * rhs.denominator + rhs.numerator * denominator, denominator * rhs.denominator)
23 elsif rhs.is_a? Integer
24 Rational(numerator + rhs * denominator, denominator)
25 elsif rhs.is_a? Numeric
26 (numerator + rhs * denominator) / denominator
32 Rational(numerator * rhs.denominator - rhs.numerator * denominator, denominator * rhs.denominator)
33 elsif rhs.is_a? Integer
34 Rational(numerator - rhs * denominator, denominator)
35 elsif rhs.is_a? Numeric
36 (numerator - rhs * denominator) / denominator
42 Rational(numerator * rhs.denominator, denominator * rhs.numerator)
43 elsif rhs.is_a? Integer
44 Rational(numerator, denominator * rhs)
45 elsif rhs.is_a? Numeric
46 numerator / rhs / denominator
51 if rhs.is_a?(Integral)
52 return numerator <=> rhs if denominator == 1
58 (numerator * rhs.denominator - denominator * rhs.numerator) <=> 0
67 return true if self.equal?(rhs)
68 if rhs.is_a?(Integral) && denominator == 1
69 return numerator == rhs
71 if rhs.is_a?(Rational)
72 numerator * rhs.denominator == denominator * rhs.numerator
86 def Rational(numerator, denominator = 1)
89 a, b = b, a % b until b == 0
90 Rational._new(numerator.div(a), denominator.div(a))
93 [:+, :-, :*, :/, :<=>, :==, :<, :<=, :>, :>=].each do |op|
94 original_operator_name = :"__original_operator_#{op}_rational"
95 Fixnum.instance_eval do
96 alias_method original_operator_name, op
97 define_method op do |rhs|
99 Rational(self).__send__(op, rhs)
101 __send__(original_operator_name, rhs)
105 Float.instance_eval do
106 alias_method original_operator_name, op
107 define_method op do |rhs|
108 if rhs.is_a? Rational
111 __send__(original_operator_name, rhs)
113 end if Object.const_defined?(:Float)