File tree 2 files changed +30
-2
lines changed
2 files changed +30
-2
lines changed Original file line number Diff line number Diff line change @@ -257,6 +257,22 @@ describe "Hash" do
257
257
a = {1 => 2 }
258
258
a.delete(2 ).should be_nil
259
259
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
260
276
end
261
277
262
278
describe " size" do
Original file line number Diff line number Diff line change @@ -198,13 +198,25 @@ class Hash(K, V)
198
198
yield value
199
199
end
200
200
201
- # Deletes the key-value pair and returns the value.
201
+ # Deletes the key-value pair and returns the value, otherwise returns `nil` .
202
202
#
203
203
# ```
204
204
# h = {"foo" => "bar"}
205
205
# h.delete("foo") # => "bar"
206
206
# h.fetch("foo", nil) # => nil
207
207
# ```
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
+ # ```
208
220
def delete (key )
209
221
index = bucket_index(key)
210
222
entry = @buckets [index]
@@ -242,7 +254,7 @@ class Hash(K, V)
242
254
previous_entry = entry
243
255
entry = entry.next
244
256
end
245
- nil
257
+ yield key
246
258
end
247
259
248
260
# Deletes each key-value pair for which the given block returns `true`.
You can’t perform that action at this time.
0 commit comments