使用哈希
从 ruby-1.9 开始,哈希键顺序得到保证。一个简单的解决方案是利用这一点,将您的请求放入哈希中并存储其结果,通过其 key 访问哈希元素:
requests = {
foo: [ 'a', 1 ],
bar: [ 'b', 5 ],
foobar: [ 'c', 2 ]
}
requests.each do |name, config|
Thread.new( name, config ) do |name, config|
sleep config[1]
requests[ name ] = config[0]
end
end
sleep 6
requests.each do |name, result|
puts "#{name} : #{result}"
end
生产:
foo : a
bar : b
foobar : c
因此,要匹配您提供的代码:
stop, i, text, requests = false, 0, '', {}
until stop
i += 1
requests[ i ] = nil
Thread.new( i ) do |key|
r = RestClient.post 'http://example.com'
requests[ i ] = r.to_str
sleep 1
# after a treatment, the value of stop will set to true
end
end
# you will have to join threads, here
text = requests.values.join
使用数组
如果最后一个示例对您有好处,您甚至可以使用数组来简化它。数组顺序当然也得到保证,您可以利用 ruby 数组动态大小特性:
a = []
a[5] = 1
p a
=> [nil, nil, nil, nil, nil, 1]
所以,前面的例子可以重写:
stop, i, text, requests = false, 0, '', []
until stop
i += 1
Thread.new( i ) do |key|
r = RestClient.post 'http://example.com'
requests[ i ] = r.to_str
sleep 1
# after a treatment, the value of stop will set to true
end
end
# you will have to join threads, here
text = requests.join