我有一个我用.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
答案 0 :(得分:8)
collection.each_with_index do |item, i|
next_item = collection[i+1] # will be nil when past the end of the collection
end