Skip to content

Commit 80692e9

Browse files
bmulvihillAry Borenszweig
authored and
Ary Borenszweig
committedJan 20, 2017
Allow block with Hash#delete
1 parent b5f0e5a commit 80692e9

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed
 

‎spec/std/hash_spec.cr

+16
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,22 @@ describe "Hash" do
257257
a = {1 => 2}
258258
a.delete(2).should be_nil
259259
end
260+
261+
describe "with block" do
262+
it "returns the value if a key is found" do
263+
a = {1 => 2}
264+
a.delete(1) { 5 }.should eq(2)
265+
end
266+
267+
it "returns the value of the block if key is not found" do
268+
a = {1 => 2}
269+
a.delete(3) { |key| key }.should eq(3)
270+
end
271+
272+
it "returns nil if key is found and value is nil" do
273+
{3 => nil}.delete(3) { 7 }.should be_nil
274+
end
275+
end
260276
end
261277

262278
describe "size" do

‎src/hash.cr

+14-2
Original file line numberDiff line numberDiff line change
@@ -198,13 +198,25 @@ class Hash(K, V)
198198
yield value
199199
end
200200

201-
# Deletes the key-value pair and returns the value.
201+
# Deletes the key-value pair and returns the value, otherwise returns `nil`.
202202
#
203203
# ```
204204
# h = {"foo" => "bar"}
205205
# h.delete("foo") # => "bar"
206206
# h.fetch("foo", nil) # => nil
207207
# ```
208+
def delete(key)
209+
delete(key) { nil }
210+
end
211+
212+
# Deletes the key-value pair and returns the value, else yields *key* with given block.
213+
#
214+
# ```
215+
# h = {"foo" => "bar"}
216+
# h.delete("foo") { |key| "#{key} not found" } # => "bar"
217+
# h.fetch("foo", nil) # => nil
218+
# h.delete("baz") { |key| "#{key} not found" } # => "baz not found"
219+
# ```
208220
def delete(key)
209221
index = bucket_index(key)
210222
entry = @buckets[index]
@@ -242,7 +254,7 @@ class Hash(K, V)
242254
previous_entry = entry
243255
entry = entry.next
244256
end
245-
nil
257+
yield key
246258
end
247259

248260
# Deletes each key-value pair for which the given block returns `true`.

0 commit comments

Comments
 (0)
Please sign in to comment.