You are not using filter_map often enough

Somewhat regularly, you will need to filter a list down to some items and then map them to another value.

You can of course chain map and compact, or select/filter and map, but Ruby 2.7 introduced a method for this exact purpose: filter_map Show archive.org snapshot .

So instead of

>> [1, 2, 3, 4, 5, 6].map { |i| i * 2 if i.even? }.compact
=> [4, 8, 12]

or

>> [1, 2, 3, 4, 5, 6].select(&:even?).map { |i| i * 2 }
=> [4, 8, 12]

you can just do

>> [1, 2, 3, 4, 5, 6].filter_map { |i| i * 2 if i.even? }
=> [4, 8, 12]

Since it's an Enumerable method, it's available for all enumerables, like Hash or Range.

See also

Arne Hartherz Almost 2 years ago