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 authored and asterite committed Jan 20, 2017
1 parent b5f0e5a commit 80692e9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 16 additions & 0 deletions spec/std/hash_spec.cr
Expand Up @@ -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
Expand Down
16 changes: 14 additions & 2 deletions src/hash.cr
Expand Up @@ -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]
Expand Down Expand Up @@ -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`.
Expand Down

0 comments on commit 80692e9

Please sign in to comment.