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

时间:2015-05-26 21:30:22

标签: ruby-on-rails ruby

我有一个我用.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

1 个答案:

答案 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