module UnitConversion class ParsedNumber attr_reader :value def initialize(str) @original_value = str @value = str.is_a?(Numeric) ? str : parse_value(str) end def to_s @value.to_s end def rational? value.is_a?(Integer) || value.is_a?(Rational) end def parse_value(str) if str =~ /^#{INTEGER_REGEX}$/ str.to_i elsif str =~ /^#{RATIONAL_REGEX}$/ parts = str.split(' ') if parts.length == 2 whole = parts.first.to_r fractional = parts.last.to_r (whole.abs + fractional) * (whole < 0 ? -1.to_r : 1.to_r) else str.to_r end elsif str =~ /^#{DECIMAL_REGEX}$/ str.to_d else raise UnparseableUnitError, "str [#{str}] is not a valid number" end end end end