diff --git a/spec/std/hash_spec.cr b/spec/std/hash_spec.cr index 54b2c3c86439..7d1fa7583b24 100644 --- a/spec/std/hash_spec.cr +++ b/spec/std/hash_spec.cr @@ -257,6 +257,25 @@ describe "Hash" do a = {1 => 2} a.delete(2).should be_nil end + + describe "with block" do + it "returns the value if a key is found" do + a = {1 => 2} + a.delete(1).should eq(2) + end + + it "executes block if key is not found" do + found = true + a = {1 => 2} + a.delete(3) { found = false } + found.should be_false + end + + it "returns the value of the block if key is not found" do + a = {1 => 2} + a.delete(3) { |key| key }.should eq(3) + end + end end describe "size" do diff --git a/src/hash.cr b/src/hash.cr index eacf0969ab1d..28272c111153 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -198,13 +198,25 @@ class Hash(K, V) yield value end - # Deletes the key-value pair and returns the value. + # Deletes the key-value pair and returns the value, otherwise returns `nil`. # # ``` # h = {"foo" => "bar"} # h.delete("foo") # => "bar" # h.fetch("foo", nil) # => nil # ``` + def delete(key) + delete(key) { nil } + end + + # Deletes the key-value pair and returns the value, else yields *key* with given block. + # + # ``` + # h = {"foo" => "bar"} + # h.delete("foo") { |key| "#{key} not found" } # => "bar" + # h.fetch("foo", nil) # => nil + # h.delete("baz") { |key| "#{key} not found" } # => "baz not found" + # ``` def delete(key) index = bucket_index(key) entry = @buckets[index] @@ -242,7 +254,7 @@ class Hash(K, V) previous_entry = entry entry = entry.next end - nil + yield key end # Deletes each key-value pair for which the given block returns `true`.