TIL: Ruby 2.7's Enumerable#filter_map
The Enumerable module is a source of wonder and crammed with so many useful methods. Today I learned about the new filter_map method
The Enumerable
module is a source of wonder and crammed with so many useful methods. Today I learned about the new filter_map
method.
Previously, if wanted to map only some part of a collection you would do something like:
# square only the even numbers in a range
arr = (1..10).to_a
mapped = arr.select(&:even?).map { |x| x ** 2 }
Ruby 2.7 introduced a way to combine both:
arr = (1..10).to_a
mapped = arr.filter_map { |x| x ** 2 if x.even? }
Only truthy values will be included.
Member discussion