Module: Converty
- Defined in:
- lib/converty.rb,
lib/converty/version.rb
Overview
Easily convert amounts between different units
Defined Under Namespace
Classes: CantConvertError, Error, UnitError
Constant Summary collapse
- DISTANCE_TYPE =
:distance- WEIGHT_TYPE =
:weight- UNITS =
{ ft: { base_per: 1.0, type: DISTANCE_TYPE }, in: { base_per: 1 / 12.0, type: DISTANCE_TYPE }, mi: { base_per: 5280.0, type: DISTANCE_TYPE }, km: { base_per: 3280.84, type: DISTANCE_TYPE }, oz: { base_per: 1.0, type: WEIGHT_TYPE }, lb: { base_per: 16.0, type: WEIGHT_TYPE } }.freeze
- VERSION =
"0.1.0"
Class Method Summary collapse
-
.convert(amount, from:, to:) ⇒ Object
Convert the specified amount in the
fromunit to the to thetounit.
Class Method Details
.convert(amount, from:, to:) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/converty.rb', line 69 def self.convert(amount, from:, to:) to_unit = UNITS[to] from_unit = UNITS[from] if to_unit.nil? || from_unit.nil? invalid_units = [] invalid_units.push(from) if from_unit.nil? invalid_units.push(to) if to_unit.nil? raise UnitError.new(invalid_units) end if to_unit.fetch(:type) != from_unit.fetch(:type) raise CantConvertError.new(from, to) end in_base = from_unit[:base_per] * amount in_base / to_unit[:base_per] end |