Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/unit/class.rb
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,17 @@ def in!(unit)
result
end

# Converts +self+ to +unit+ and returns the bare numeric value, dropping
# the dimension. Builds on +#in!+, so a dimensionally incompatible +unit+
# raises +TypeError+ rather than returning a coerced number with residual
# units.
#
# Unit(1, "kilometer").value_in("meter") # => 1000
# Unit(1, "meter").value_in("volt") # raises TypeError
def value_in(unit)
in!(unit).value
end

def inspect
unit.empty? ? %{Unit("#{value}")} : %{Unit("#{value_string} #{unit_string('.')}")}
end
Expand Down
9 changes: 9 additions & 0 deletions spec/unit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,15 @@
expect(Unit(1, "kilometer/hour").in("meter/second")).to eq(Unit(5, 18, 'meter/second'))
end

it 'should extract the bare value in a target unit' do
expect(Unit(1, "kilometer").value_in("meter")).to eq(1000)
expect(Unit(1, "kilometer/hour").value_in("meter/second")).to eq(Rational(5, 18))
end

it 'should raise when value_in is given an incompatible unit' do
expect { Unit(1, "meter").value_in("second") }.to raise_error(TypeError)
end

it 'should have a working compatible? method' do
expect(Unit(7, "meter").compatible?('kilogram')).to eq(false)
expect(Unit(3, "parsec").compatible_with?('meter')).to eq(true)
Expand Down