Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby loop skipping elements

Tags:

ruby

I have this:

puts pids
pids.each do |pid|
    puts "Running on pid #{pid}"
    begin
        Process::kill(0, pid)
        puts "Pid #{pid} still alive"
    rescue Errno::ESRCH
        puts "Pid #{pid} now dead!!!!"
        pids.delete(pid)
        running_jobs -= 1
        puts "Remaining jobs: #{running_jobs}"
    end
end

which outputs this:

25555
25579
25616
Running on pid 25555
Pid 25555 now dead!!!!
Remaining jobs: 2
Running on pid 25616
Pid 25616 now dead!!!!
Remaining jobs: 1    

As you can see, the loop is never executed on the middle element. Can anyone tell me why that happens that way? I need to really loop over every item and handle it accordingly.

like image 728
jeffcook2150 Avatar asked Dec 10 '22 02:12

jeffcook2150


1 Answers

You are mutating the array as you iterate over it with pids.delete(pid) So you are on 25555 at index 0, then you delete it, causing the array to look like [25579, 25616]. Then you iterate, now you are at index 1, which is 25616. If you simply remove the delete, you will no longer be mutating the array and the iteration will work as expected.

like image 200
Joshua Cheek Avatar answered Dec 25 '22 07:12

Joshua Cheek