From f494b8418c8d4bf3c4c24bb71f01927bb04c83b2 Mon Sep 17 00:00:00 2001 From: Bryan Mulvihill Date: Fri, 6 Jan 2017 20:55:01 -0500 Subject: [PATCH] Allow block with Hash#delete --- spec/std/hash_spec.cr | 16 ++++++++++++++++ src/hash.cr | 16 ++++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/spec/std/hash_spec.cr b/spec/std/hash_spec.cr index 54b2c3c86439..24d86900c76a 100644 --- a/spec/std/hash_spec.cr +++ b/spec/std/hash_spec.cr @@ -257,6 +257,22 @@ 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) { 5 }.should eq(2) + 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 + + it "returns nil if key is found and value is nil" do + {3 => nil}.delete(3) { 7 }.should be_nil + 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`.