Deleting items from an array requires multiple passes to remove them all

前端 未结 2 719
一个人的身影
一个人的身影 2021-02-13 12:35

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.

So I tried this:

         


        
2条回答
  •  忘掉有多难
    2021-02-13 12:41

    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.

    Try reject instead.

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

提交回复
热议问题