Method: RubyUnits::Unit#+
- Defined in:
- lib/ruby_units/unit.rb
#+(other) ⇒ Unit
Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible. It is possible to add Time objects to units of time
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 |
# File 'lib/ruby_units/unit.rb', line 822 def +(other) case other when Unit if zero? other.dup elsif self =~ other raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?) if [self, other].any?(&:temperature?) if temperature? RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature) else RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature) end else @q ||= (Rational(@@cached_units[units].scalar, @@cached_units[units].base_scalar) rescue units.to_unit.to_base.scalar) RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar) * @q, numerator: @numerator, denominator: @denominator, signature: @signature) end else raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" end when Date, Time raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit' else x, y = coerce(other) y + x end end |