Commit 3e7db4ad authored by Jun Hiroe's avatar Jun Hiroe

Add Hash#delete_if

parent 8e4d3bb9
......@@ -27,4 +27,27 @@ class Hash
self[key]
end
end
##
# call-seq:
# hsh.delete_if {| key, value | block } -> hsh
# hsh.delete_if -> an_enumerator
#
# Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
# evaluates to <code>true</code>.
#
# If no block is given, an enumerator is returned instead.
#
# h = { "a" => 100, "b" => 200, "c" => 300 }
# h.delete_if {|key, value| key >= "b" } #=> {"a"=>100}
#
def delete_if(&block)
return to_enum :delete_if unless block_given?
self.each do |k, v|
self.delete(k) if block.call(k, v)
end
self
end
end
......@@ -39,3 +39,37 @@ assert('Hash#fetch') do
assert_kind_of(StandardError, e);
end
end
assert("Hash#delete_if") do
base = { 1 => 'one', 2 => false, true => 'true', 'cat' => 99 }
h1 = { 1 => 'one', 2 => false, true => 'true' }
h2 = { 2 => false, 'cat' => 99 }
h3 = { 2 => false }
h = base.dup
assert_equal(h, h.delete_if { false })
assert_equal({}, h.delete_if { true })
h = base.dup
assert_equal(h1, h.delete_if {|k,v| k.instance_of?(String) })
assert_equal(h1, h)
h = base.dup
assert_equal(h2, h.delete_if {|k,v| v.instance_of?(String) })
assert_equal(h2, h)
h = base.dup
assert_equal(h3, h.delete_if {|k,v| v })
assert_equal(h3, h)
h = base.dup
n = 0
h.delete_if {|*a|
n += 1
assert_equal(2, a.size)
assert_equal(base[a[0]], a[1])
h.shift
true
}
assert_equal(base.size, n)
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment