Ruby 2.7 adds Enumerable#filter_map

Ashik Salman

Ashik Salman

May 8, 2020

This blog is part of our  Ruby 2.7 series.

Ruby 2.7 adds Enumerable#filter_map which is a combination of filter + map as the name indicates. The 'filter_map' method filters and map the enumerable elements within a single iteration.

Before Ruby 2.7, we could have achieved the same with 2 iterations using select & map combination or map & compact combination.

1
2irb> numbers = [3, 6, 7, 9, 5, 4]
3
4# we can use select & map to find square of odd numbers
5
6irb> numbers.select { |x| x.odd? }.map { |x| x**2 }
7=> [9, 49, 81, 25]
8
9# or we can use map & compact to find square of odd numbers
10
11irb> numbers.map { |x| x**2 if x.odd? }.compact
12=> [9, 49, 81, 25]
13

Ruby 2.7

Ruby 2.7 adds Enumerable#filter_map which can be used to filter & map the elements in a single iteration and which is more faster when compared to other options described above.

1irb> numbers = [3, 6, 7, 9, 5, 4]
2irb> numbers.filter_map { |x| x**2 if x.odd? }
3=> [9, 49, 81, 25]
4

The original discussion had started 8 years back. Here is the latest thread and github commit for reference.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.