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.
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 |