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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)