Commit 9beef5fd authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto

Merge pull request #1923 from ksss/hash-enumerator-select

Hash#{select,select!} support return Enumerator
parents 85d20127 d09e4475
...@@ -494,6 +494,20 @@ assert 'Hash#each_value' do ...@@ -494,6 +494,20 @@ assert 'Hash#each_value' do
assert_equal [1,2], {a:1,b:2}.each_value.to_a.sort assert_equal [1,2], {a:1,b:2}.each_value.to_a.sort
end end
assert 'Hash#select' do
h = {1=>2,3=>4,5=>6}
hret = h.select.with_index {|a,b| a[1] == 4}
assert_equal({3=>4}, hret)
assert_equal({1=>2,3=>4,5=>6}, h)
end
assert 'Hash#select!' do
h = {1=>2,3=>4,5=>6}
hret = h.select!.with_index {|a,b| a[1] == 4}
assert_equal h, hret
assert_equal({3=>4}, h)
end
assert 'Range#each' do assert 'Range#each' do
a = (1..5) a = (1..5)
b = a.each b = a.each
......
...@@ -162,10 +162,12 @@ class Hash ...@@ -162,10 +162,12 @@ class Hash
# 1.9 Hash#select! returns Hash; ISO says nothing. # 1.9 Hash#select! returns Hash; ISO says nothing.
def select!(&b) def select!(&b)
return to_enum :select! unless block_given?
keys = [] keys = []
self.each_key{|k| self.each_key{|k|
v = self[k] v = self[k]
unless b.call(k, v) unless b.call([k, v])
keys.push(k) keys.push(k)
end end
} }
...@@ -178,10 +180,12 @@ class Hash ...@@ -178,10 +180,12 @@ class Hash
# 1.9 Hash#select returns Hash; ISO says nothing. # 1.9 Hash#select returns Hash; ISO says nothing.
def select(&b) def select(&b)
return to_enum :select unless block_given?
h = {} h = {}
self.each_key{|k| self.each_key{|k|
v = self[k] v = self[k]
if b.call(k, v) if b.call([k, v])
h[k] = v h[k] = v
end 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