获取.each循环中的下一个项目,而不结束当前项目的迭代

mik*_*h77 1 ruby ruby-on-rails

我有一个集合,我正在循环中.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
Run Code Online (Sandbox Code Playgroud)

sma*_*thy 8

collection.each_with_index do |item, i|
  next_item = collection[i+1]   # will be nil when past the end of the collection
end
Run Code Online (Sandbox Code Playgroud)