如何修改一个数组,而我在Ruby中遍历呢? [英] How do I modify an array while I am iterating over it in Ruby?
问题描述
我只是学习Ruby所以道歉,如果这太为新手在这里,但我不能从书中镐头工作了这一点(可能只是不读书不够仔细)。
无论如何,如果我有一个数组,像这样:
I'm just learning Ruby so apologies if this is too newbie for around here, but I can't work this out from the pickaxe book (probably just not reading carefully enough). Anyway, if I have an array like so:
arr = [1,2,3,4,5]
...我想,说,3阵列中的每个乘以价值,我曾指出,执行以下操作:
...and I want to, say, multiply each value in the array by 3, I have worked out that doing the following:
arr.each {|item| item *= 3}
...不会得到我我想要的(我明白为什么,我不修改数组本身)。
...will not get me what I want (and I understand why, I'm not modifying the array itself).
我不明白的是如何从迭代后,code块内修改原始数组。我敢肯定,这是很容易的。
What I don't get is how to modify the original array from inside the code block after the iterator. I'm sure this is very easy.
推荐答案
使用地图
从旧创建一个新的数组:
Use map
to create a new array from the old one:
arr2 = arr.map {|item| item * 3}
使用地图
修改到位数组:
arr.map! {|item| item * 3}
请参阅它的在线工作: ideone
See it working online: ideone
这篇关于如何修改一个数组,而我在Ruby中遍历呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!