Map an array modifying only elements matching a certain condition

前端 未结 9 2210
梦如初夏
梦如初夏 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:20

    I've found that the best way to accomplish this is by using tap

    arr = [1,2,3,4,5,6]
    [].tap do |a|
      arr.each { |x| a << x if x%2==0 }
    end
    

提交回复
热议问题