简单的Ruby循环数组不会完全迭代

时间:2021-01-30 21:21:32

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

所以我认为我理解这一点,但我没有得到我预期的输出,所以显然我不理解它。

In Ruby (2.0.0)

在Ruby(2.0.0)

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

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.delete(e)的某些机制正在影响迭代。

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!

如何通过遍历每个项目并删除它来获取此循环?谢谢!

2 个解决方案

#1


3  

With

a = [1,2,3,4]
a.each do |e|
  a.delete(e)
end
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].

第一次迭代是在索引0处,e为1.正在删除,a变为[2,3,4],下一次迭代在索引1,e为3.即被删除,a变为[2,4] 。下一次迭代将在索引2处,但由于a不再那么长,它会停止,返回值为[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]

#2


6  

DO NOT mutate a collection when you iterate over it, unless you know what you are doing.

除非你知道自己在做什么,否则不要在迭代时改变集合。

For your ultimate purpose,

为了您的最终目的,

a = [1,2,3,4]
a.reject!{|e| e < 3 }

#1


3  

With

a = [1,2,3,4]
a.each do |e|
  a.delete(e)
end
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].

第一次迭代是在索引0处,e为1.正在删除,a变为[2,3,4],下一次迭代在索引1,e为3.即被删除,a变为[2,4] 。下一次迭代将在索引2处,但由于a不再那么长,它会停止,返回值为[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]

#2


6  

DO NOT mutate a collection when you iterate over it, unless you know what you are doing.

除非你知道自己在做什么,否则不要在迭代时改变集合。

For your ultimate purpose,

为了您的最终目的,

a = [1,2,3,4]
a.reject!{|e| e < 3 }