如何在循环收集集合时从集合中获取下一条记录?例如
for record in collection
current_value = record.value
next_value = record.next.value #==> Would like this!
# more stuff with record
end
答案 0 :(得分:1)
你应该能够这样做:
collection.each_with_index do |record, index|
current_value = record.value
next_value = collection[index+1].value
# more stuff
end
答案 1 :(得分:1)
查看Enumerable#each_cons
(DataMapper::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
,它会从集合中产生非重叠的组。