Method: UnitMeasurements::Unit#parse_value

Defined in:
lib/unit_measurements/unit.rb

#parse_value(tokens) ⇒ Array<Numeric, String> (private)

Parses tokens and returns a conversion value and the unit.

This method is used internally to parse the conversion value of the unit while calculating the conversion factor. It handles cases where the value can be provided as a string or an array containing a number and a unit.

For example, if the value is provided as a string in the form of “10 m”, it will be parsed to return 10.0 as the conversion value and “m” as the unit.

This method returns conversion value in rational number to avoid precision errors and frozen string of unit name.

Parameters:

  • tokens (String|Array)

    The value to be parsed. It can be either a string or an array containing a number and a unit.

Returns:

  • (Array<Numeric, String>)

    The array of conversion value and the unit.

Raises:

  • (BaseError)

    if tokens is not an instance of Array or String, or tokens array contains more than two elements.

See Also:

Author:

Since:

  • 1.2.0



231
232
233
234
235
236
237
238
239
240
241
# File 'lib/unit_measurements/unit.rb', line 231

def parse_value(tokens)
  case tokens
  when String
    tokens = Parser.parse(value)
  when Array
    raise BaseError, "Cannot parse [number, unit] formatted tokens from #{tokens}." unless tokens.size == 2
  else
    raise BaseError, "Value of the unit must be defined as string or array, but received #{tokens}"
  end
  [tokens[0].to_r, tokens[1].freeze]
end