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

前端 未结 2 699
一个人的身影
一个人的身影 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 }
    
    0 讨论(0)
  • 2021-02-13 12:41

    There is another way to do the same as reject! with delete:

    list.delete_if { |item| item =~  /cat|dog|rat/i }
    
    0 讨论(0)
提交回复
热议问题