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

前端 未结 4 837
轻奢々
轻奢々 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 11:04

    You don't have to delete from the array, you can filter it so:

    a = [1, 2, 3, 4, 5]
    
    b = a.select {|x| x < 3}
    
    puts b.inspect # => [1,2]
    
    b.each {|i| puts i} # do something to each here
    

提交回复
热议问题