From 186afcbd906243bae1964743474eda30cabcba22 Mon Sep 17 00:00:00 2001 From: Kevin Olbrich Date: Wed, 26 Sep 2018 10:11:39 -0400 Subject: [PATCH] Fixes #174 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. --- lib/ruby_units/unit.rb | 4 ++-- spec/ruby_units/unit_spec.rb | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/ruby_units/unit.rb b/lib/ruby_units/unit.rb index 32d4e188..5b03e66c 100644 --- a/lib/ruby_units/unit.rb +++ b/lib/ruby_units/unit.rb @@ -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}')" @@ -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}')" diff --git a/spec/ruby_units/unit_spec.rb b/spec/ruby_units/unit_spec.rb index c02cd766..6ea4805f 100644 --- a/spec/ruby_units/unit_spec.rb +++ b/spec/ruby_units/unit_spec.rb @@ -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 @@ -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