summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-rational/mrblib/rational.rb
blob: 2c71f43f504164157fe047aeeefa7e0cc7b21e65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Rational < Numeric
  def inspect
    "(#{to_s})"
  end

  def to_s
    "#{numerator}/#{denominator}"
  end

  def <=>(rhs)
    case rhs
    when Integer, Float
      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
end

class Numeric
  def to_r
    Rational(self, 1)
  end
end