2012-03-14 1 views

답변

1

당신은 그런 식으로 일을 할 수 있어야한다 :

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

컬렉션의 마지막 항목이이 코드를 위반합니다. 물론, 이것은 원래 질문에서도 그렇지만, 어쨌든. –

1

Enumerable#each_cons 봐 (DataMapper::CollectionEnumerable 포함) 유무 :

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