Class: Rational

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

Instance Method Summary collapse

Methods inherited from Numeric

#+@, #-@, #abs, #integer?, #negative?, #nonzero?, #positive?, #to_c, #to_r, #zero?

Methods included from Comparable

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

Instance Method Details

#<=>(other) ⇒ Object

call-seq:

rat <=> numeric -> -1, 0, +1, or nil

Returns -1, 0, or +1 depending on whether rat is less than, equal to, or greater than numeric. This is the basis for the tests in the Comparable module. Returns nil if the two values are incomparable.

Rational(2, 3) <=> Rational(2, 3)  #=> 0
Rational(5) <=> 5                  #=> 0
Rational(2, 3) <=> Rational(1, 3)  #=> 1
Rational(1, 3) <=> 1               #=> -1
Rational(1, 3) <=> 0.3             #=> 1


44
45
46
47
48
49
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 44

def <=>(other)
  return nil unless other.kind_of?(Numeric)
  self.to_f <=> other.to_f
rescue
  nil
end

#inspectObject

call-seq:

rat.inspect -> string

Returns the value as a string for inspection.

Rational(2).inspect      #=> "(2/1)"
Rational(-8, 6).inspect  #=> "(-4/3)"
Rational(1, 2).inspect   #=> "(1/2)"


12
13
14
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 12

def inspect
  "(#{to_s})"
end

#to_sObject

call-seq:

rat.to_s -> string

Returns the value as a string.

Rational(2).to_s      #=> "2/1"
Rational(-8, 6).to_s  #=> "-4/3"
Rational(1, 2).to_s   #=> "1/2"


26
27
28
# File 'mrbgems/mruby-rational/mrblib/rational.rb', line 26

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