Reputation: 802
I have a collection that I'm cycling through with an .each
loop. Is there a way to get the next value without breaking the current iteration for a particular item in the collection?
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
Upvotes: 2
Views: 3586
Reputation: 27971
collection.each_with_index do |item, i|
next_item = collection[i+1] # will be nil when past the end of the collection
end
Upvotes: 9