【发布时间】:2012-03-02 12:30:21
【问题描述】:
我有这个:
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
输出这个:
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
如您所见,循环永远不会在中间元素上执行。谁能告诉我为什么会这样?我真的需要遍历每个项目并相应地处理它。
【问题讨论】:
-
您不想在迭代同一个集合时删除集合中的元素。 (我认为这在大多数编程语言中通常是正确的。)除了@klochner 关于您的具体情况的帖子之外,请参阅这些帖子以了解在 Ruby 中从数组中删除所选项目的其他方法:stackoverflow.com/questions/3260686/…stackoverflow.com/questions/2933366/…跨度>
-
出于某种原因,我觉得我已经能够在我编写的其他程序中做到这一点。稍后我将不得不试一试。我是 Ruby 新手,感谢您的帮助。
标签: ruby