Class: EyeOfNewt::Quantity

Inherits:
Object
  • Object
show all
Defined in:
lib/eye_of_newt/quantity.rb

Constant Summary collapse

DELTA =
0.01
SIGNIFICANT_DIGITS =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(amount, unit, modifier: nil, units: EyeOfNewt.units) ⇒ Quantity

Returns a new instance of Quantity.



10
11
12
13
14
15
# File 'lib/eye_of_newt/quantity.rb', line 10

def initialize(amount, unit, modifier: nil, units: EyeOfNewt.units)
  @amount = amount
  @units = units
  @unit = units[unit]
  @modifier = modifier
end

Instance Attribute Details

#amountObject (readonly)

Returns the value of attribute amount.



8
9
10
# File 'lib/eye_of_newt/quantity.rb', line 8

def amount
  @amount
end

#modifierObject (readonly)

Returns the value of attribute modifier.



8
9
10
# File 'lib/eye_of_newt/quantity.rb', line 8

def modifier
  @modifier
end

#unitObject (readonly)

Returns the value of attribute unit.



8
9
10
# File 'lib/eye_of_newt/quantity.rb', line 8

def unit
  @unit
end

#unitsObject (readonly)

Returns the value of attribute units.



8
9
10
# File 'lib/eye_of_newt/quantity.rb', line 8

def units
  @units
end

Instance Method Details

#in(new_unit) ⇒ Object



17
18
19
20
21
# File 'lib/eye_of_newt/quantity.rb', line 17

def in(new_unit)
  rate = units.conversion_rate(unit, new_unit)
  new_amount = range? ? amount.map{|a| a * rate} : amount * rate
  self.class.new(new_amount, new_unit, units: units)
end

#to_sObject Also known as: inspect



23
24
25
26
# File 'lib/eye_of_newt/quantity.rb', line 23

def to_s
  amount_str = range? ? amount.map{|a| fraction_str(a)}.join('') : fraction_str(amount)
  [amount_str, modifier, unit_str].compact.join(' ')
end