Ruby find next in array

Array includes Enumerable, so you can use each_with_index:

elements.each_with_index {|element, index|
   next_element = elements[index+1]
   do_something unless next_element.nil?
   ...

}

A nice way to iterate over an Enumerable if you need to access both an element and the next one is using each_cons:

arr = [1, 2, 3]
arr.each_cons(2) do |element, next_element|
   p "#{element} is followed by #{next_element}"
   #...
end

# => "1 is followed by 2", "2 is followed by 3".

As pointed out by Phrogz, Enumerable#each_cons is available in Ruby 1.8.7+; for Ruby 1.8.6 you can require 'backports/1.8.7/enumerable/each_cons'.

As @Jacob points out, the other approach is to use each_with_index.

Tags:

Arrays

Ruby