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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)