Implement `filter_map` from Ruby2.6.

parent 57a0132b
...@@ -826,5 +826,17 @@ module Enumerable ...@@ -826,5 +826,17 @@ module Enumerable
end end
hash.values hash.values
end end
def filter_map(&blk)
return to_enum(:find_index, val) unless blk
ary = []
self.each do |x|
x = blk.call(x)
ary.push x if x
end
ary
end
alias filter select alias filter select
end end
...@@ -188,3 +188,8 @@ assert("Enumerable#to_h") do ...@@ -188,3 +188,8 @@ assert("Enumerable#to_h") do
assert_equal h0, h assert_equal h0, h
assert_equal({1=>4,3=>8}, c.new.to_h{|k,v|[k,v*2]}) assert_equal({1=>4,3=>8}, c.new.to_h{|k,v|[k,v*2]})
end end
assert("Enumerable#filter_map") do
assert_equal [4, 8, 12, 16, 20], (1..10).filter_map{|i| i * 2 if i%2==0}
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