Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Hash#update when default block also adds given key #14417

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 spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,17 @@ describe "Hash" do
h[3000].should eq(3000 + 42)
end

it "doesn't create a duplicate key, if key does not exist and default block adds the given key (#14416)" do
h = Hash(String, Int32).new do |h, new_key|
h[new_key] = 1
new_key.size
end

h.update("new key") { |v| v * 6 }
h.size.should eq(1)
h["new key"].should eq(7 * 6)
end

it "inserts a new entry using the default value as input, if key does not exist" do
h = Hash(String, Int32).new(2)

Expand Down
4 changes: 3 additions & 1 deletion src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1144,7 +1144,9 @@ class Hash(K, V)
entry.value
elsif block = @block
default_value = block.call(self, key)
insert_new(key, yield default_value)

# NOTE: can't use `#insert_new` as `block` might add arbitrary keys
upsert(key, yield default_value)
default_value
else
raise KeyError.new "Missing hash key: #{key.inspect}"
Expand Down
Loading