Map an array modifying only elements matching a certain condition

前端 未结 9 2220
梦如初夏
梦如初夏 2021-02-05 09:07

In Ruby, what is the most expressive way to map an array in such a way that certain elements are modified and the others left untouched?

This is a straight-forw

9条回答
  •  故里飘歌
    2021-02-05 09:15

    Ruby 2.7+

    As of 2.7 there's a definitive answer.

    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!

提交回复
热议问题