From aee758ce3360c98e2947579a1078400ece65cbad 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 | 9 +++++++++ src/hash.cr | 18 +++++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/spec/std/hash_spec.cr b/spec/std/hash_spec.cr index 54b2c3c86439..3ee161d33604 100644 --- a/spec/std/hash_spec.cr +++ b/spec/std/hash_spec.cr @@ -257,6 +257,15 @@ describe "Hash" do a = {1 => 2} a.delete(2).should be_nil end + + describe "with block" do + it "executes block if key is not found" do + found = true + a = {1 => 2} + a.delete(3) { found = false } + found.should be_false + end + end end describe "size" do diff --git a/src/hash.cr b/src/hash.cr index eacf0969ab1d..5e4452c9efed 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -198,7 +198,23 @@ 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, 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, &block) + if val = delete(key) + val + else + yield key + end + end + + # Deletes the key-value pair and returns the value, otherwise returns `nil`. # # ``` # h = {"foo" => "bar"}