Class: Measurement::UnitGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/measurement/unit_group.rb

Overview

This class is a group of units. To specify that a unit is in a group pass the group option to Measurement::Base#unit

Instance Method Summary collapse

Constructor Details

#initialize(units) ⇒ UnitGroup

Returns a new instance of UnitGroup.



5
6
7
# File 'lib/measurement/unit_group.rb', line 5

def initialize(units)
  @units = units.sort.reverse
end

Instance Method Details

#baseObject



9
10
11
# File 'lib/measurement/unit_group.rb', line 9

def base
  @units.first
end

#format(amount, precision = 0) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/measurement/unit_group.rb', line 13

def format(amount, precision = 0)
  units = @units.dup
  strs = []
  precision = 0 if units.size > 1
  
  while unit = units.shift
    n_in = unit.to(amount)
    n_in = n_in.floor unless units.empty?
    n_out = unit.from(n_in)
    amount -= n_out
    strs << unit.format(n_out, precision) unless n_out == 0
  end
  
  strs.join(' ')
end

#from(amount) ⇒ Object



29
30
31
# File 'lib/measurement/unit_group.rb', line 29

def from(amount)
  @units.first.from(amount)
end

#to(amount) ⇒ Object



33
34
35
# File 'lib/measurement/unit_group.rb', line 33

def to(amount)
  @units.first.to(amount)
end