Map an array modifying only elements matching a certain condition

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

    If you don't need the old array, I prefer map! in this case because you can use the ! method to represent you are changing the array in place.

    self.answers.map!{ |x| (x=="b" ? x+"!" : x) }
    

    I prefer this over:

    new_map = self.old_map{ |x| (x=="b" ? x+"!" : x) }
    

提交回复
热议问题