---
title: "Ruby 2.7 adds Enumerable#filter_map"
description: "Ruby 2.7 adds Enumerable#filter_map"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-filter-map"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-filter-map.md"
---

# Ruby 2.7 adds Enumerable#filter_map

Ruby 2.7 adds Enumerable#filter_map

- Author: Ashik Salman
- Published: May 8, 2020
- Categories: Ruby 2.7, Ruby

Ruby 2.7 adds
[Enumerable#filter_map](https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-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.

```ruby

irb> numbers = [3, 6, 7, 9, 5, 4]

# we can use select & map to find square of odd numbers

irb> numbers.select { |x| x.odd? }.map { |x| x**2 }
=> [9, 49, 81, 25]

# or we can use map & compact to find square of odd numbers

irb> numbers.map { |x| x**2 if x.odd? }.compact
=> [9, 49, 81, 25]

```

#### 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.

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

```

The original discussion had started
[8 years back](https://bugs.ruby-lang.org/issues/5663). Here is the latest
[thread](https://bugs.ruby-lang.org/issues/15323) and
[github commit](https://github.com/ruby/ruby/pull/2017/commits/38e04e15bf1d4e67c52630fa3fca1d4a056ea768)
for reference.

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-7-adds-enumerable-filter-map)
