Skip to content

Commit

Permalink
Fix Hash#reject! for non-equality key (#10511)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored Jun 3, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 9b8870c commit 1597576
Showing 2 changed files with 25 additions and 3 deletions.
22 changes: 22 additions & 0 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
@@ -767,6 +767,11 @@ describe "Hash" do
h2.should_not be(h1)
end

it "select with non-equality key" do
h = {Float64::NAN => true, 0.0 => true}
h.select { |k| !k.nan? }.should eq({0.0 => true})
end

it "selects!" do
h1 = {:a => 1, :b => 2, :c => 3}

@@ -776,6 +781,12 @@ describe "Hash" do
h2.should be(h1)
end

it "select! with non-equality key" do
h = {Float64::NAN => true, 0.0 => true}
h.select! { |k| !k.nan? }
h.should eq({0.0 => true})
end

it "rejects" do
h1 = {:a => 1, :b => 2, :c => 3}

@@ -784,6 +795,11 @@ describe "Hash" do
h2.should_not be(h1)
end

it "reject with non-equality key" do
h = {Float64::NAN => true, 0.0 => true}
h.reject(&.nan?).should eq({0.0 => true})
end

it "rejects!" do
h1 = {:a => 1, :b => 2, :c => 3}

@@ -793,6 +809,12 @@ describe "Hash" do
h2.should be(h1)
end

it "reject with non-equality key" do
h = {Float64::NAN => true, 0.0 => true}
h.reject!(&.nan?)
h.should eq({0.0 => true})
end

it "compacts" do
h1 = {:a => 1, :b => 2, :c => nil}

6 changes: 3 additions & 3 deletions src/hash.cr
Original file line number Diff line number Diff line change
@@ -1502,9 +1502,9 @@ class Hash(K, V)
end

# Equivalent to `Hash#reject`, but makes modification on the current object rather than returning a new one. Returns `self`.
def reject!(& : K, V ->) : self
each do |key, value|
delete(key) if yield(key, value)
def reject!(& : K, V -> _)
each_entry_with_index do |entry, index|
delete_entry_and_update_counts(index) if yield(entry.key, entry.value)
end
self
end

0 comments on commit 1597576

Please sign in to comment.