Method: RubyUnits::Unit#-

Defined in:
lib/ruby_units/unit.rb

#-(other) ⇒ Unit

Subtract two units. Result is same units as receiver and scalar and base_scalar are updated appropriately

Parameters:

Returns:

Raises:

  • (ArgumentError)

    when subtracting a temperature from a degree

  • (ArgumentError)

    when units are not compatible

  • (ArgumentError)

    when subtracting a fixed time from a time span



741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'lib/ruby_units/unit.rb', line 741

def -(other)
  case other
    when Unit
      case
        when self.zero?
          if other.zero?
            other.dup * -1 # preserve Units class
          else
            -other.dup
          end
        when self =~ other
          case
            when [self, other].all? { |x| x.is_temperature? }
              RubyUnits::Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => KELVIN, :denominator => UNITY_ARRAY, :signature => @signature).convert_to(self.temperature_scale)
            when self.is_temperature?
              RubyUnits::Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => ['<tempK>'], :denominator => UNITY_ARRAY, :signature => @signature).convert_to(self)
            when other.is_temperature?
              raise ArgumentError, "Cannot subtract a temperature from a differential degree unit"
            else
              @q ||= ((@@cached_units[self.units].scalar / @@cached_units[self.units].base_scalar) rescue (self.units.unit.scalar/self.units.unit.to_base.scalar))
              RubyUnits::Unit.new(:scalar => (self.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 Time
      raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be subtracted from to a Unit, which can only represent time spans"
    else
      x, y = coerce(other)
      return y-x
  end
end