Implement filter_map from Ruby2.6.

This commit is contained in:
Yukihiro "Matz" Matsumoto
2019-09-16 08:01:08 +09:00
parent 57a0132b41
commit d380c7d26f
2 changed files with 17 additions and 0 deletions
+12
View File
@@ -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
+5
View File
@@ -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