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 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