在迭代时添加到数组 [英] Adding to an Array while Iterating

查看:100
本文介绍了在迭代时添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码'锁定'红宝石?什么是超越它的最佳方式?我在下面发布了解决方案。还有另一种方法吗?提前致谢!

Why does this code 'lock up' ruby? And what is the best way to get past it? I posted my solution below. Is there another way to do this? Thanks in advance!

代码:

nums = [1, 2, 3] 
nums.each { |i| nums << i + 1 }

我的解决方案:

nums = [1, 2, 3]
adjustments = []
nums.each { |i| adjustments << i + 1 }
nums += adjustments 


推荐答案

那是因为每个人都使用一个枚举器(所以如果你继续添加它就永远不会到达终点)。

That's because each uses an enumerator (so it never reaches the end if you keep adding to it).

你可以在应用每个数组之前复制数组。

You can duplicate the array before applying each.

nums = [1, 2, 3] 
nums.dup.each { |i| nums << i + 1 }

另一种方法是追加map给出的额外元素:

Another way is to append the extra elements given by map:

nums = [1, 2, 3] 
nums += nums.map { |i|  i + 1 }

这篇关于在迭代时添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆