Commit dcad562f authored by Jun Hiroe's avatar Jun Hiroe

Add Hash#keep_if

parent 1ce9060f
......@@ -137,4 +137,27 @@ class Hash
self.each {|k, v| h[v] = k }
h
end
##
# call-seq:
# hsh.keep_if {| key, value | block } -> hsh
# hsh.keep_if -> an_enumerator
#
# Deletes every key-value pair from <i>hsh</i> for which <i>block</i>
# evaluates to false.
#
# If no block is given, an enumerator is returned instead.
#
def keep_if(&block)
return to_enum :keep_if unless block_given?
keys = []
self.each do |k, v|
unless block.call([k, v])
self.delete(k)
end
end
self
end
end
......@@ -95,3 +95,10 @@ assert("Hash#invert") do
assert_include(%w[a c], h[1])
assert_equal('b', h[2])
end
assert("Hash#keep_if") do
h = { 1 => 2, 3 => 4, 5 => 6 }
assert_equal({3=>4,5=>6}, h.keep_if {|k, v| k + v >= 7 })
h = { 1 => 2, 3 => 4, 5 => 6 }
assert_equal({ 1 => 2, 3=> 4, 5 =>6} , h.keep_if { true })
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