現在の項目の反復を終了せずに、.each ループ内の次の項目を取得します。
概要
.each ループを使用して循環しているコレクションがあります。コレクション内の特定の項目の現在の反復を中断せずに次の値を取得する方法はありますか?
collection = [foo, bar, quux]
collection.each do |item|
# Print the current iteration "foo"
p item #should return foo
# Also print the next iteration "bar"
# without breaking the current each loop for "foo"
p item.something_to_get_bar
end
解決策
collection.each_with_index do |item, i|
next_item = collection[i+1] # will be nil when past the end of the collection
end