在迭代时添加到数组

编程入门 行业动态 更新时间:2024-10-26 21:35:33
本文介绍了在迭代时添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 }

更多推荐

在迭代时添加到数组

本文发布于:2023-10-10 22:50:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!