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
8 changes: 6 additions & 2 deletions lib/unit/class.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,10 @@ def ==(other)
other = coerce_numeric(other)
a, b = self.normalize, other.normalize
a.value == b.value && a.unit == b.unit
else
elsif other.respond_to?(:coerce)
apply_through_coercion(other, __method__)
else
false
end
end

Expand All @@ -132,8 +134,10 @@ def <=>(other)
other = coerce_numeric_compatible(other)
a, b = self.normalize, other.normalize
a.value <=> b.value
else
elsif other.respond_to?(:coerce)
apply_through_coercion(other, __method__)
else
nil
end
end

Expand Down
24 changes: 24 additions & 0 deletions spec/unit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@
expect(Unit(2)).to be > UnitOne.new
end

it "should return false from == for objects that are not comparable" do
expect(Unit(1) == nil).to be false
expect(Unit(1) == "string").to be false
expect(Unit(1) == []).to be false
expect(Unit(1) == :symbol).to be false
expect(Unit(1)).not_to eq(nil)
expect(Unit(1)).not_to eq("string")
end

it "should treat != consistently with ==" do
expect(Unit(1) != nil).to be true
expect(Unit(1) != "string").to be true
end

it "should return nil from <=> for objects that are not comparable" do
expect(Unit(1) <=> nil).to be_nil
expect(Unit(1) <=> "string").to be_nil
end

it "should raise ArgumentError for ordered comparison with incomparable objects" do
expect { Unit(1) > nil }.to raise_error(ArgumentError)
expect { Unit(1) < "string" }.to raise_error(ArgumentError)
end

it "should support eql comparison" do
expect(Unit(1)).to eql(Unit(1))
expect(Unit(1.0)).not_to eql(Unit(1))
Expand Down
Loading