Read more

You are not using filter_map often enough

Arne Hartherz
May 23, 2022Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2022-05-23 14:23)