Map an array modifying only elements matching a certain condition

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

    Because arrays are pointers, this also works:

    a = ["hello", "to", "you", "dude"]
    a.select {|i| i.length <= 3 }.each {|i| i << "!" }
    
    puts a.inspect
    # => ["hello", "to!", "you!", "dude"]
    

    In the loop, make sure you use a method that alters the object rather than creating a new object. E.g. upcase! compared to upcase.

    The exact procedure depends on what exactly you are trying to achieve. It's hard to nail a definite answer with foo-bar examples.

提交回复
热议问题