如何在集合中循环时获取集合中的下一条记录?例如。ruby Datamapper:从集合中获取下一条记录
for record in collection
current_value = record.value
next_value = record.next.value #==> Would like this!
# more stuff with record
end
如何在集合中循环时获取集合中的下一条记录?例如。ruby Datamapper:从集合中获取下一条记录
for record in collection
current_value = record.value
next_value = record.next.value #==> Would like this!
# more stuff with record
end
你应该能够做到这样的:
collection.each_with_index do |record, index|
current_value = record.value
next_value = collection[index+1].value
# more stuff
end
看一看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
,它从集合中产生非重叠的组。
这很好。但是,集合中的最后一个元素永远不会分配给'a [0]'。 – fatnic 2012-03-14 22:18:25
集合中的最后一项将打破此代码。当然,原来的问题也是如此,但无论如何。 – 2012-03-14 13:49:27