You are not using filter_map often enough

Posted . Visible to the public.

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
Last edit
Henning Koch
Keywords
array, hash, list
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2022-05-23 12:23)