在 Ruby 中迭代数组时如何修改数组?
我刚刚学习 Ruby,所以很抱歉,如果这对这里来说太新手了,但我无法从镐书中解决这个问题(可能只是没有仔细阅读)。 无论如何,如果我有一个像这样的数组:
arr = [1,2,3,4,5]
...并且我想将数组中的每个值乘以 3,我已经发现执行以下操作:
arr.each {|item| item *= 3}
...不会得到我想要的(并且我明白为什么,我没有修改数组本身)。
我不明白的是如何从迭代器之后的代码块内部修改原始数组。我确信这很容易。
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]
...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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
map
从旧数组创建新数组:使用
map!
就地修改数组:查看它在线工作:ideone
Use
map
to create a new array from the old one:Use
map!
to modify the array in place:See it working online: ideone
要直接修改数组,请使用arr.map! {|项目|项目*3}。要基于原始数组创建新数组(这通常是更好的选择),请使用 arr.map {|item|项目*3}。事实上,在使用
each
之前我总是三思而后行,因为通常会有一个高阶函数,如map
、select
或inject< /code> 这就是我想要的。
To directly modify the array, use
arr.map! {|item| item*3}
. To create a new array based on the original (which is often preferable), usearr.map {|item| item*3}
. In fact, I always think twice before usingeach
, because usually there's a higher-order function likemap
,select
orinject
that does what I want.其他人已经提到 array.map 是这里更优雅的解决方案,但您可以简单地添加一个“!”到 array.each 的末尾,您仍然可以修改数组。添加“!”到#map、#each、#collect等结束都会修改现有的数组。
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.