In Ruby, is there an Array method that combines 'select' and 'map'?

后端 未结 14 790
盖世英雄少女心
盖世英雄少女心 2020-12-07 18:34

I have a Ruby array containing some string values. I need to:

  1. Find all elements that match some predicate
  2. Run the matching elements through a transfo
14条回答
  •  有刺的猬
    2020-12-07 19:30

    Ruby 2.7+

    There is now!

    Ruby 2.7 is introducing filter_map for this exact purpose. It's idiomatic and performant, and I'd expect it to become the norm very soon.

    For example:

    numbers = [1, 2, 5, 8, 10, 13]
    enum.filter_map { |i| i * 2 if i.even? }
    # => [4, 16, 20]
    

    Here's a good read on the subject.

    Hope that's useful to someone!

提交回复
热议问题