This class represents a Value with a numeric value and a Unit. The numeric value can be any Numeric, though it is not recommended to use Values.
A Value can be added to, subtracted from and multiplied with another value, though only when both Values are using the same Converter. While multiplication is always possible, adding or subtracting values with incompatible Units results in a TypeError. When two Units are compatible but not the same, the Value with the larger of the Units is converted to the smaller of the Units. For example adding 100 seconds and 1 minute, the latter is converted to 60 seconds because a second is smaller than a minute. The result is 160 seconds.
[R] | unit | The Unit of this value. |
[R] | value | The numeric value of this Value. |
Creates a new Value with the given numeric value and the given unit. Simply returns the given value if the given unit is valueless, i.e., when unit.unitless? is true.
[ show source ]
# File lib/facets/more/units.rb, line 234 def self.new(value, unit) return value if unit.unitless? super end
[ show source ]
# File lib/facets/more/units.rb, line 245 def converter unit.converter end
Alias for to_s
[ show source ]
# File lib/facets/more/units.rb, line 291 def method_missing(m, *args, &blk) if self.converter.registered?(m) raise ArgumentError, "Wrong number of arguments" if args.length != 0 return self * Value.new(1, Units::Unit.new({m => 1}, self.converter)) end super end
Converts this Value to the given Unit. This only works if the Converters used by this Value’s Unit and the given Unit are the same. It obviously fails if the Units are not compatible (can’t add apples and oranges).
[ show source ]
# File lib/facets/more/units.rb, line 273 def to(to_unit) conv1, conv2 = unit.coerce(to_unit) raise TypeError, "incompatible units for operation" if conv1.units != conv2.units mult = conv1.multiplier / conv2.multiplier Value.new(value * mult, to_unit) end
Returns a human readable string representation.
[ show source ]
# File lib/facets/more/units.rb, line 285 def to_s "#{@value} #{@unit}" end
[ show source ]
# File lib/facets/more/units.rb, line 301 def do_additive_op(op, other) if other.is_a? Value conv1, conv2 = unit.coerce(other.unit) raise TypeError, "incompatible units for #{op}" if conv1.units != conv2.units mult = conv2.multiplier / conv1.multiplier if mult > 1 Value.new(value.send(op, other.value * mult), unit) else Value.new(other.value.send(op, value * mult), other.unit) end else raise TypeError, "incompatible operands for #{op}" end end
[ show source ]
# File lib/facets/more/units.rb, line 316 def do_multiplicative_op(op, other) if other.is_a? Value Value.new(value.send(op, other.value), unit.send(op, other.unit)) elsif other.is_a? Units::Unit Value.new(value, unit.send(op, other)) else Value.new(value.send(op, other), unit) end end