我有一个非常不寻常的行为,q.pop的返回obj没有相应更新。我将使用伪代码演示......
q = Queue.new
insert unique objects into the q...
while !q.empty? do
curr = q.pop
req = Typhoeus::Request.new("someLegitURL")
req.on_complete do |response|
puts curr #PROBLEM: same result every time!!!
end
end
^这里,我面临的问题是,当我“放入curr”时,每次对象都是一样的!
如果我用这样的数组替换SAME代码:
arr = Array.new
insert unique objects into the arr...
arr.each do |curr|
... same thing ...
puts curr # NOT A PROBLEM: different result every time
... same thing ...
end
^在这里,我实际上为“puts curr”获得了独特的输出。
有没有人遇到这样的问题?
对问题/解决方案的任何见解?
感谢。
答案 0 :(得分:1)
问题解决了!如果以后有人需要,我会回答我自己的问题。
问题: Ruby非常不寻常地使用while循环。
在Ruby的while循环中,循环的每次迭代都不会消亡。这就是我的意思
while true
i = 10
break
end
puts i # this will actually print out 10
然而
loop do
i = 10
break
end
puts i # raises error
简而言之:当我使用带队列的while循环时,问题是前一循环的迭代没有被“擦除”,从而影响以后的迭代。
如有疑问,请使用循环,而不是使用循环。