How can I use Array#delete while iterating over the array?

前端 未结 4 839
轻奢々
轻奢々 2020-12-24 10:21

I have an array that I want to iterate over and delete some of the elements. This doesn\'t work:

a = [1, 2, 3, 4, 5]
a.each do |x|
  next if x < 3
  a.del         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 10:54

    Another way to do it is using reject!, which is arguably clearer since it has a ! which means "this will change the array". The only difference is that reject! will return nil if no changes were made.

    a.delete_if {|x| x >= 3 }
    

    or

    a.reject! {|x| x >= 3 }
    

    will both work fine.

提交回复
热议问题