class EyeOfNewt::Quantity

Constants

DELTA
SIGNIFICANT_DIGITS

Attributes

amount[R]
modifier[R]
unit[R]
units[R]

Public Class Methods

new(amount, unit, modifier: nil, units: EyeOfNewt.units) click to toggle source
# 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

Public Instance Methods

in(new_unit) click to toggle source
# 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
inspect()
Alias for: to_s
to_s() click to toggle source
# 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
Also aliased as: inspect

Private Instance Methods

fraction_str(a) click to toggle source
# File lib/eye_of_newt/quantity.rb, line 35
def fraction_str(a)
  return nil if units.unquantified?(unit)
  fraction = to_fraction(a)
  whole = fraction.to_i
  fractional = fraction - whole
  [whole, fractional].reject(&:zero?).join(' ')
end
range?() click to toggle source
# File lib/eye_of_newt/quantity.rb, line 31
def range?
  amount.is_a?(Array)
end
signif(value, digits) click to toggle source
# File lib/eye_of_newt/quantity.rb, line 53
def signif(value, digits)
  Float("%.#{digits}g" % value)
end
to_fraction(a) click to toggle source
# File lib/eye_of_newt/quantity.rb, line 49
def to_fraction(a)
  signif(a, SIGNIFICANT_DIGITS).to_r.rationalize(DELTA)
end
unit_str() click to toggle source
# File lib/eye_of_newt/quantity.rb, line 43
def unit_str
  return nil if unit == units.default
  singular = range? ? amount.last <= 1 : amount <= 1
  singular ? unit.singularize : unit
end