Exploring Ruby-2.7.0 — Part-Three

Tessy Joseph
The MavenHive Blog
Published in
1 min readJun 10, 2019

Ruby-2.7 adds Enumerable#filter_map

ruby-2.7 adds filter_map which combines filter and map in one iteration.

Let us suppose you have a collection of employee records. Assume you have to get the employee_id’s of all contract employees. This could be achieved using filter_map

using filter and map to fetch all the employee_ids of contract employees.

Before ruby.27.0

using select and map to fetch all the employee_ids of contract employees.
using map and then compact to fetch all the employee_ids of contract employees

Why you must use filter_map?

  1. There would be a significant speedup as filter_map performs the operation in a single iteration
  2. By using filter_map your code looks more elegant to read
  3. filter_map could come very handy when manipulating Active Record object collections

I am adding more examples from the test cases

filter_map examples

The only caveat is it would be impossible to intentionally return nil.

if you are interested how filter_map is implemented check this github link

--

--