简单的Ruby遍历数组不完全遍历 [英] Simple Ruby loop through array does not iterate completely

查看:490
本文介绍了简单的Ruby遍历数组不完全遍历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想我明白这一点,但我没有得到我预期的输出,所以很明显,我不明白。

So I thought I understood this, but I'm not getting the output I expected, so obviously I don't understand it.

在红宝石(2.0.0)

In Ruby (2.0.0)

a = [1,2,3,4]
a.each do |e|
    a.delete(e)
end
a = [2,4]

它似乎没有通过阵列中的每个项目被循环。然而,当我简单地输出项目,它遍历每个项目。有a.delete(E)的某些机制是影响迭代。

It doesn't seem to be looping through each item in the array. However, when I simply output the item, it loops through each item. There's some mechanism of a.delete(e) that is affecting the iteration.

a = [1,2,3,4]
a.each do |e|
    puts e
end
=> 1
=> 2
=> 3
=> 4

最后,我想提出一个条件进入死循环,如:

Ultimately, I want to put a conditional into the loop, such as:

a = [1,2,3,4]
a.each do |e|
    if e < 3
        a.delete(e)
    end
end

我怎样才能得到这个循环通过每个项目迭代并删除它吗?谢谢!

How can I get this loop it iterate through each item and delete it? Thank you!

推荐答案

通过

a = [1,2,3,4]
a.each do |e|
  a.delete(e)
end
a # => [2, 4]

第一次迭代是在指数 0 电子 1 。这被删除, A 变成 [2,3,4] 和下一个迭代是指数 1 电子 3 。这被删除, A 变成 [2,4] 。下一次迭代将处于指数 2 ,但由于 A 是不是长了,它会停止,返回 A 的值 [2,4]

The first iteration was at index 0 with e being 1. That being deleted, a becomes [2,3,4] and the next iteration is at index 1, with e being 3. That being deleted, a becomes [2,4]. The next iteration would be at index 2, but since a is not that long anymore, it stops, returning a's value as [2, 4].

为了通过每个项目迭代并删除它,因为没有重复的,常见的方式是向后遍历。

In order to iterate through each item and delete it, given that there is no duplicate, a common way is to iterate backwards.

a = [1,2,3,4]
a.reverse_each do |e|
  a.delete(e)
end
a # => []

a = [1,2,3,4]
a.reverse_each do |e|
  if e < 3
    a.delete(e)
  end
end
a # => [3, 4]

这篇关于简单的Ruby遍历数组不完全遍历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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