Class: Rational

Inherits:
Numeric show all
Defined in:
mrbgems/mruby-rational/mrblib/rational.rb

Instance Method Summary collapse

Methods inherited from Numeric

#+@, #-@, #abs, #finite?, #infinite?, #negative?, #nonzero?, #positive?, #to_r, #zero?

Methods included from Comparable

#<, #<=, #>, #>=, #between?, #clamp

Instance Method Details

#*(rhs) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 10

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) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 20

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) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 30

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) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 40

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) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 50

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) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 66

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

#inspectObject



2
3
4
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 2

def inspect
  "(#{to_s})"
end

#to_sObject



6
7
8
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 6

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