krunal shah krunal shah - 2 months ago 16
Ruby Question

Iterate over a array and returning the next and the element before current

How may i fetch next and before current element from array while iterating array with each.

array.each do |a|
# I want to fetch next and before current element.
end

Answer

Take look at Enumerable#each_cons method:

[nil, *array, nil].each_cons(3){|prev, curr, nxt|
  puts "prev: #{prev} curr: #{curr} next: #{nxt}"
}

prev:  curr: a next: b
prev: a curr: b next: c
prev: b curr: c next: 

If you like, you can wrap it in new Array method:

class Array
  def each_with_prev_next &block
    [nil, *self, nil].each_cons(3, &block)
  end
end
#=> nil

array.each_with_prev_next do |prev, curr, nxt|
  puts "prev: #{prev} curr: #{curr} next: #{nxt}"
end