开发者

Iterate over a array and returning the next and the element before current [duplicate]

开发者 https://www.devze.com 2023-01-18 06:56 出处:网络
This question already has answers here: Ruby array access 2 consecutive(chained) elements at a time (4 answers)
This question already has answers here: Ruby array access 2 consecutive(chained) elements at a time (4 answers) Closed 3 years ago.

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

array.each do |a|
   # I w开发者_开发技巧ant to fetch next and before current element.
end


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消