Map an array modifying only elements matching a certain condition

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

    It's a few lines long, but here's an alternative for the hell of it:

    oa = %w| a b c |
    na = oa.partition { |a| a == 'b' }
    na.first.collect! { |a| a+'!' }
    na.flatten! #Add .sort! here if you wish
    p na
    # >> ["b!", "a", "c"]
    

    The collect with ternary seems best in my opinion.

提交回复
热议问题