Commit 02cabf8f authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #2198 from suzukaze/add-hash.keep_if

Add Hash#keep_if
parents e620c666 dcad562f
...@@ -137,4 +137,27 @@ class Hash ...@@ -137,4 +137,27 @@ class Hash
self.each {|k, v| h[v] = k } self.each {|k, v| h[v] = k }
h h
end 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 end
...@@ -95,3 +95,10 @@ assert("Hash#invert") do ...@@ -95,3 +95,10 @@ assert("Hash#invert") do
assert_include(%w[a c], h[1]) assert_include(%w[a c], h[1])
assert_equal('b', h[2]) assert_equal('b', h[2])
end 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