Class: Ratio

Inherits:
Object show all
Includes:
Comparable
Defined in:
lib/epitools/ratio.rb

Overview

The ratio between two numbers (eg: 2:1, 3:4)

Can be compared, added, “percent”ed, “to_f”ed, and displayed.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first, last = 1) ⇒ Ratio

`first` is the top part of the ratio, `last` is the bottom (eg: `first/last`)


23
24
25
26
# File 'lib/epitools/ratio.rb', line 23

def initialize(first, last=1)
  @first = first
  @last = last
end

Instance Attribute Details

#firstObject

Returns the value of attribute first


14
15
16
# File 'lib/epitools/ratio.rb', line 14

def first
  @first
end

#lastObject

Returns the value of attribute last


14
15
16
# File 'lib/epitools/ratio.rb', line 14

def last
  @last
end

Class Method Details

.[](*args) ⇒ Object


16
17
18
# File 'lib/epitools/ratio.rb', line 16

def self.[](*args)
  new(*args)
end

Instance Method Details

#+(other) ⇒ Object

Adds together the tops and bottoms of the ratios.

Example: For the ratios `a/c` and `b/d`, returns `a+b/c+d`


67
68
69
# File 'lib/epitools/ratio.rb', line 67

def +(other)
  Ratio.new( first+other.first, last+other.last)
end

#<=>(other) ⇒ Object


10
11
12
# File 'lib/epitools/ratio.rb', line 10

def <=>(other)
  to_f <=> other.to_f
end

#inspectObject

“#<Ratio: 1/2>”


58
59
60
# File 'lib/epitools/ratio.rb', line 58

def inspect
  "#<Ratio: #{to_s}>"
end

#percentObject Also known as: to_percent

Returns a string representing the number in percent


50
51
52
# File 'lib/epitools/ratio.rb', line 50

def percent
  "%0.1f%%" % (to_f * 100)
end

#to_fObject

Returns the ratio as a float. (eg: Ratio.to_f == 0.5)


39
40
41
42
43
44
45
# File 'lib/epitools/ratio.rb', line 39

def to_f
  if @last == 0
    0.0
  else
    @first.to_f / @last
  end
end

#to_sObject Also known as: ratio

Returns a string representation: “a/b”


31
32
33
# File 'lib/epitools/ratio.rb', line 31

def to_s
  "#{@first}/#{@last}"
end