Skip to content

Commit

Permalink
Allow block with Hash#delete
Browse files Browse the repository at this point in the history
  • Loading branch information
bmulvihill committed Jan 8, 2017
1 parent d1f8c42 commit aee758c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
9 changes: 9 additions & 0 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 17 additions & 1 deletion src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down

0 comments on commit aee758c

Please sign in to comment.