Skip to content

Commit

Permalink
Fix unitless addition and subtraction (#175)
Browse files Browse the repository at this point in the history
When adding or subtracting two unitless numbers, the result used to be 
converted to the same units as the receiver.  This didn't work if the 
receiver was unitless.  The fix changes the way we do the conversion in 
a way that is not subject to this problem.
  • Loading branch information
olbrich authored Sep 26, 2018
1 parent 8c3b1fb commit 1f44b20
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/ruby_units/unit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -847,7 +847,7 @@ def +(other)
RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature)
end
else
RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).to(units)
RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
Expand Down Expand Up @@ -883,7 +883,7 @@ def -(other)
elsif other.temperature?
raise ArgumentError, 'Cannot subtract a temperature from a differential degree unit'
else
RubyUnits::Unit.new(scalar: (base_scalar - other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).to(units)
RubyUnits::Unit.new(scalar: (base_scalar - other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
Expand Down
8 changes: 8 additions & 0 deletions spec/ruby_units/unit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1744,6 +1744,10 @@
context 'between a degree and a temperature' do
specify { expect(RubyUnits::Unit.new('100 degK') + RubyUnits::Unit.new('100 tempK')).to eq(RubyUnits::Unit.new('200 tempK')) }
end

context 'between two unitless units' do
specify { expect(RubyUnits::Unit.new('1') + RubyUnits::Unit.new('2')).to eq 3 }
end
end

context 'subtracting (-)' do
Expand Down Expand Up @@ -1784,6 +1788,10 @@
context 'between a degree and a temperature' do
specify { expect { (RubyUnits::Unit.new('100 degK') - RubyUnits::Unit.new('100 tempK')) }.to raise_error(ArgumentError, 'Cannot subtract a temperature from a differential degree unit') }
end

context 'a unitless unit from another unitless unit' do
specify { expect(RubyUnits::Unit.new('1') - RubyUnits::Unit.new('2')).to eq -1 }
end
end

context 'multiplying (*)' do
Expand Down

0 comments on commit 1f44b20

Please sign in to comment.