Module: ConverterChain

Included in:
Calcpace
Defined in:
lib/calcpace/converter_chain.rb

Overview

Module for chaining multiple unit conversions

This module allows performing multiple conversions in sequence, which is useful for complex unit transformations.

Instance Method Summary collapse

Instance Method Details

#convert_chain(value, conversions) ⇒ Float

Performs a chain of conversions on a value

Examples:

Convert kilometers to miles to feet

convert_chain(1, [:km_to_mi, :mi_to_feet])
#=> 3280.84 (1 km = 0.621 mi = 3280.84 feet)

Using string format

convert_chain(100, ['meters to km', 'km to mi'])
#=> 0.0621371 (100 m = 0.1 km = 0.0621 mi)

Parameters:

  • value (Numeric)

    the initial value to convert

  • conversions (Array<Symbol, String>)

    array of conversion units

Returns:

  • (Float)

    the final converted value

Raises:



23
24
25
26
27
28
# File 'lib/calcpace/converter_chain.rb', line 23

def convert_chain(value, conversions)
  check_positive(value, 'Value')
  conversions.reduce(value) do |result, conversion|
    result * constant(conversion)
  end
end

#convert_chain_with_description(value, conversions) ⇒ Hash

Performs a chain of conversions and returns a description

Examples:

convert_chain_with_description(1, [:km_to_mi, :mi_to_feet])
#=> { result: 3280.84, description: "1.0 → km_to_mi → mi_to_feet → 3280.84" }

Parameters:

  • value (Numeric)

    the initial value to convert

  • conversions (Array<Symbol, String>)

    array of conversion units

Returns:

  • (Hash)

    hash with :result and :description keys



39
40
41
42
43
44
45
46
# File 'lib/calcpace/converter_chain.rb', line 39

def convert_chain_with_description(value, conversions)
  initial_value = value
  result = convert_chain(value, conversions)
  conversion_names = conversions.join('')
  description = "#{initial_value}#{conversion_names}#{result.round(4)}"

  { result: result, description: description }
end