Class: UOM::Measurement

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/uom/measurement.rb

Overview

Measurement qualifies a quantity with a unit.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(unit, quantity) ⇒ Measurement

Creates a new Measurement with the given quantity and unit label, e.g.:

Measurement.new(:mg, 4) #=> 4 mg


16
17
18
19
20
21
# File 'lib/uom/measurement.rb', line 16

def initialize(unit, quantity)
  unit = UOM::Unit.for(unit) if Symbol === unit
  @quantity = quantity
  @unit = unit
  @unit_alias = unit unless unit == @unit.label
end

Instance Attribute Details

#quantityObject (readonly)

Returns the value of attribute quantity.



12
13
14
# File 'lib/uom/measurement.rb', line 12

def quantity
  @quantity
end

#unitObject (readonly)

Returns the value of attribute unit.



12
13
14
# File 'lib/uom/measurement.rb', line 12

def unit
  @unit
end

Instance Method Details

#*(other) ⇒ Object

Returns the product of this measurement and the other measurement or Numeric. If other is a Measurement, then the returned Measurement Unit is the product of this Measurement’s unit and the other Measurement’s unit.



40
41
42
# File 'lib/uom/measurement.rb', line 40

def *(other)
  compose(:*, other)
end

#/(other) ⇒ Object

Returns the quotient of this measurement and the other measurement or Numeric. If other is a Measurement, then the returned Measurement Unit is the quotient of this Measurement’s unit and the other Measurement’s unit.



47
48
49
# File 'lib/uom/measurement.rb', line 47

def /(other)
  compose(:/, other)
end

#==(other) ⇒ Object



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

def ==(other)
  return quantity == other unless Measurement === other
  unit == other.unit ? quantity == other.quantity : other.as(unit) == self
end

#as(unit) ⇒ Object

Returns a new Measurement which expresses this measurement as the given unit.



52
53
54
55
56
# File 'lib/uom/measurement.rb', line 52

def as(unit)
  unit = UOM::Unit.for(unit.to_sym) if String === unit or Symbol === unit
  return self if @unit == unit
  Measurement.new(unit, @unit.as(quantity, unit))
end

#to_sObject



58
59
60
61
62
63
# File 'lib/uom/measurement.rb', line 58

def to_s
  unit = @unit_alias || unit.to_s(quantity)
  unit_s = unit.to_s
  suffix = quantity == 1 ? unit_s : unit_s.pluralize
  "#{quantity} #{suffix}"
end