14

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
krunal shah
  • 16,089
  • 25
  • 97
  • 143
  • 1
    Two questions: 1) What is the "previous" element at the beginning and the "next" element at the end? 2) Should the `next` element be the `current` element of the next iteration (that is, after the group `[ar[4], ar[5], ar[6]]`, should the next group be `[ar[5], ar[6], ar[7]]` or `[ar[7], ar[8], ar[9]]`)? – Chuck Sep 29 '10 at 19:31

2 Answers2

41

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
David Chouinard
  • 6,466
  • 8
  • 43
  • 61
Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113
14

You can use Enumerable#each_with_index to get the index of each element as you iterate, and use that to get the surrounding items.

array.each_with_index do |a, i|
  prev_element = array[i-1] unless i == 0
  next_element = array[i+1] unless i == array.size - 1
end
cweston
  • 11,297
  • 19
  • 82
  • 107
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153