在 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).
我不明白的是如何在迭代器之后从代码块内部修改原始数组.我相信这很容易.
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.
推荐答案
使用 map
从旧数组创建一个新数组:
Use map
to create a new array from the old one:
arr2 = arr.map {|item| item * 3}
使用map!
就地修改数组:
arr.map! {|item| item * 3}
在线查看:ideone
这篇关于在 Ruby 中迭代数组时如何修改数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!