在 Ruby 中迭代一个数组时如何修改它?

我只是在学习 Ruby,所以如果这对于这里来说太新鲜了,我很抱歉,但是我不能从鹤嘴锄的书中解决这个问题(可能只是不够仔细地阅读)。 无论如何,如果我有一个这样的数组:

arr = [1,2,3,4,5]

... 我想把数组中的每个值乘以3我计算出如下结果:

arr.each {|item| item *= 3}

... 不会得到我想要的(我知道为什么,我没有修改数组本身)。

我不明白的是如何在迭代器之后从代码块内部修改原始数组。我相信这很简单。

72775 次浏览

Use map to create a new array from the old one:

arr2 = arr.map {|item| item * 3}

Use map! to modify the array in place:

arr.map! {|item| item * 3}

See it working online: ideone

To directly modify the array, use arr.map! {|item| item*3}. To create a new array based on the original (which is often preferable), use arr.map {|item| item*3}. In fact, I always think twice before using each, because usually there's a higher-order function like map, select or inject that does what I want.

arr.collect! {|item| item * 3}

Others have already mentioned that array.map is the more elegant solution here, but you can simply add a "!" to the end of array.each and you can still modify the array. Adding "!" to the end of #map, #each, #collect, etc. will modify the existing array.