ruby 以四人为一组处理数组元素 [英] ruby working on array elements in groups of four
问题描述
当每个元素都需要处理时,我有一个 ruby 脚本数组:
I have a ruby script array when each element needs processing :
threads = []
elemets.each do |element|
threads.push(Thread.new{process(element)}}
end
threads.each { |aThread| aThread.join }
然而,由于资源限制,如果一次不再处理四个元素,脚本将以最佳方式工作.
how ever due to resource limitations, the script works in an optimal way if no more the four elements are processed at a time.
不,我知道我可以转储每个循环并使用变量来计算 4 个元素然后等待但是有没有更酷的红宝石方式来做到这一点?
no I know I can dump the each loop and use a variable to count 4 elements and then wait but is there a cooler ruby way to do it ?
推荐答案
您可以为一个数组以 4 个为一组进行枚举:
You can enumerate in groups of 4 for an array:
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].each_slice(4) {|a| p a}
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
所以你可以尝试类似的东西
So you can try something like
elements.each_slice(4) do | batch |
batch.each do | element |
threads.push(Thread.new{process(element)}}
end
(do stuff to check to see if the threads are done, otherwise wait )
end
不过,这可能不是您需要的 - 我从凌晨 3 点起就起床,只睡了几个小时.:/
Its may not be what you need, though - I have been up since 3 AM and I only had a couple of hours sleep. :/
这篇关于ruby 以四人为一组处理数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!