2012-03-14 64 views

回答

1

你应该能够做到这样的:

collection.each_with_index do |record, index| 
    current_value = record.value 
    next_value = collection[index+1].value 
    # more stuff 
end 
+0

集合中的最后一项将打破此代码。当然,原来的问题也是如此,但无论如何。 – 2012-03-14 13:49:27

1

看一看Enumerable#each_consDataMapper::Collection包括Enumerable):

collection.each_cons(2) do |a| 
    #here a is a 2 element array: 
    current_value = a[0] 
    next_value = a[1] #(or just use the array elements directly) 

end 

使用each_cons意味着你不必担心检查集合中的最后一个元素。

还有类似的each_slice,它从集合中产生非重叠的组。

+0

这很好。但是,集合中的最后一个元素永远不会分配给'a [0]'。 – fatnic 2012-03-14 22:18:25