Class: Ratio
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
-
#first ⇒ Object
Returns the value of attribute first.
-
#last ⇒ Object
Returns the value of attribute last.
Class Method Summary collapse
Instance Method Summary collapse
-
#+(other) ⇒ Object
Adds together the tops and bottoms of the ratios.
- #<=>(other) ⇒ Object
-
#initialize(first, last = 1) ⇒ Ratio
constructor
‘first` is the top part of the ratio, `last` is the bottom (eg: `first/last`).
-
#inspect ⇒ Object
“#<Ratio: 1/2>”.
-
#percent ⇒ Object
(also: #to_percent)
Returns a string representing the number in percent.
-
#to_f ⇒ Object
Returns the ratio as a float.
-
#to_s ⇒ Object
(also: #ratio)
Returns a string representation: “a/b”.
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
#first ⇒ Object
Returns the value of attribute first.
14 15 16 |
# File 'lib/epitools/ratio.rb', line 14 def first @first end |
#last ⇒ Object
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 |
#inspect ⇒ Object
“#<Ratio: 1/2>”
58 59 60 |
# File 'lib/epitools/ratio.rb', line 58 def inspect "#<Ratio: #{to_s}>" end |
#percent ⇒ Object 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_f ⇒ Object
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_s ⇒ Object 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 |