每次树迭代都会触发一个事件

时间:2011-06-22 13:40:58

标签: ruby-on-rails ruby arrays performance iteration

我正在使用Ruby on Rails 3.0.7,我想知道迭代一个由大量数据组成的数组并在每次三次迭代时触发事件的常用做法\技术。

我可以做这样的事情

# "fire_the_event" is a method
count = 0
array.each do |element|
  count += 1

  fire_the_event if count % 3 == 0
end

但是fire_the_event每个三次时有一种“更好”,“性能更高”的方式?

2 个答案:

答案 0 :(得分:3)

您可以使用each_slice方法

array.each_slice(3) do |elements|
  fire_the_event
end

答案 1 :(得分:-2)

您的示例代码不完整,因为它没有说明您真正需要的内容。

基本上,您的代码执行以下操作:

(array.length / 3).times{fire_the_event}

但我怀疑这是你真正需要的。

无论如何,请看看这个问题:How do you select every nth item in an array?

如果您确实需要遍历每个元素,请使用with_index

array.each_with_index do |element, index|
  # perform something with each element

  # but fire the event only with every third:
  fire_the_event if index % 3 == 0
end