从数组中删除项目需要多次通过才能将它们全部删除 [英] Deleting items from an array requires multiple passes to remove them all

查看:44
本文介绍了从数组中删除项目需要多次通过才能将它们全部删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大约 1200 个 ruby​​ 对象的数组,我想遍历它们并删除名称中包含单词或单词部分的对象.

I have an array of ~1200 ruby objects and I want to loop over them and delete the ones with names that contain words or parts of words.

所以我尝试了这个:

list.each do |item|
  if item.name =~ /cat|dog|rat/i
    puts item.name
    list.delete(item)
  end
end

它有效,只是它似乎遗漏了一些名称应该匹配的项目.如果我再次运行它,它会发现更多,如果我再次运行它,它会发现更多.每次都发现较少,但我必须运行 3 次才能删除所有内容.

It works, except that it seems to miss some items with names that should match. If I run it again it finds a few more, and if I run it another time it finds a few more. It finds less each time, but I have to run it 3 times in order to delete everything.

为什么会发生这种情况?

Why in the world is this happening?

推荐答案

这就是在迭代基础集合的同时修改它.
基本上,如果集合在迭代过程中以某种方式发生变化(变空、添加新元素等),迭代器没有很多方法来处理它.

That's you modifying underlying collection while iterating over it.
Basically, if collection changes in some way during iteration (becomes empty, gets prepended with a new element, etc), iterator doesn't have a lot of ways to handle it.

尝试拒绝.

list.reject! {|item| item.name =~ /cat|dog|rat/i }

这篇关于从数组中删除项目需要多次通过才能将它们全部删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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