Map an array modifying only elements matching a certain condition

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

    One liner:

    ["a", "b", "c"].inject([]) { |cumulative, i| i == "b" ? (cumulative << "#{i}!") : cumulative }
    

    In the code above, you start with [] "cumulative". As you enumerate through an Enumerator (in our case the array, ["a", "b", "c"]), cumulative as well as "the current" item get passed to our block (|cumulative, i|) and the result of our block's execution is assigned to cumulative. What I do above is keep cumulative unchanged when the item isn't "b" and append "b!" to cumulative array and return it when it is a b.

    There is an answer above that uses select, which is the easiest way to do (and remember) it.

    You can combine select with map in order to achieve what you're looking for:

     arr = ["a", "b", "c"].select { |i| i == "b" }.map { |i| "#{i}!" }
     => ["b!"]
    

    Inside the select block, you specify the conditions for an element to be "selected". This will return an array. You can call "map" on the resulting array to append the exclamation mark to it.

提交回复
热议问题