class Base

Attributes

unit[RW]
value[RW]

Public Class Methods

new(value, unit, valid_units, precision = 16) click to toggle source
# File lib/convert_unit/base.rb, line 5
def initialize(value, unit, valid_units, precision = 16)
  raise TypeError, 'no implicit conversion of String into Integer' unless value.is_a? Numeric
  raise TypeError, 'Invalid Unit Type' unless valid_units.include?(unit.to_s.downcase)
  @value = BigDecimal.new value, precision
  @unit = unit.downcase
end

Public Instance Methods

+(other) click to toggle source
# File lib/convert_unit/base.rb, line 22
def +(other)
  b_to_a = other.to(unit)
  self.class.new(value + b_to_a.value, unit)
end
-(other) click to toggle source
# File lib/convert_unit/base.rb, line 27
def -(other)
  b_to_a = other.to(unit)
  self.class.new(value - b_to_a.value, unit)
end
==(other) click to toggle source
# File lib/convert_unit/base.rb, line 12
def ==(other)
  a_to_b = one_unit_a_to_b(unit, other.unit) * value
  b_to_a = one_unit_a_to_b(other.unit, unit) * other.value
  a_to_b == other.value || b_to_a == value
end
===(other) click to toggle source
# File lib/convert_unit/base.rb, line 18
def ===(other)
  value == other.value && unit == other.unit
end
inspect() click to toggle source
# File lib/convert_unit/base.rb, line 32
def inspect
  "#{value} #{unit}"
end
to_c() click to toggle source
# File lib/convert_unit/base.rb, line 36
def to_c
  "#{value.to_c} #{unit}"
end
to_f() click to toggle source
# File lib/convert_unit/base.rb, line 44
def to_f
  "#{value.to_f} #{unit}"
end
to_i() click to toggle source
# File lib/convert_unit/base.rb, line 48
def to_i
  "#{value.to_i} #{unit}"
end
to_r() click to toggle source
# File lib/convert_unit/base.rb, line 40
def to_r;
  "#{value.to_r} #{unit}"
end
to_s() click to toggle source
# File lib/convert_unit/base.rb, line 52
def to_s
  "#{value.to_s} #{unit}"
end

Protected Instance Methods

convert_to(c_unit) click to toggle source
# File lib/convert_unit/base.rb, line 63
def convert_to(c_unit)
  one_unit_a_to_b(unit, c_unit) * value
end
one_unit_a_to_b(unit_a, unit_b) click to toggle source
# File lib/convert_unit/base.rb, line 58
def one_unit_a_to_b(unit_a, unit_b)
  conversion_rate = @conversion_rate_for_one_unit[unit_a][unit_b]
  format('%<value>f', value: conversion_rate).to_f
end