Ruby 2.7 adds Enumerable#filter_map.
filter_map is a shorthand for
map in a single call.
Originally suggested 7 years ago,
it was addressing a common idiom
to map over an Enumerable,
but only include the elements
that match a particular filter
Another common approach is selecting + mapping,
which is pretty common, for example in
when manipulating loaded records:
It’s also possible to achieve something similar with:
We can now use
Enumerable#filter_map in Ruby 2.7 to achieve this:
As you see,
filter_map creates a new array
after first filtering desired results,
and then maps to get expected Array.
This comes in pretty handy for creating mapped
arrays in a simpler way.
It also gives us a bit of a speedup from its previous counter-parts
As you can see, this is faster with about 10-20% speedup.