迭代一个数组并在当前之前返回next和元素

kru*_*hah 12 ruby arrays

我如何在迭代数组时从数组中获取当前元素的下一个和之前的数据.

array.each do |a|
   # I want to fetch next and before current element.
end
Run Code Online (Sandbox Code Playgroud)

Mla*_*vić 37

看一下Enumerable#each_cons方法:

[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: 
Run Code Online (Sandbox Code Playgroud)

如果您愿意,可以将其包装在新的Array方法中:

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
Run Code Online (Sandbox Code Playgroud)

  • 怎么样`[nil,*array,nil]`而不是`[nil] + array + [nil]`? (3认同)

Dan*_*uis 11

您可以Enumerable#each_with_index在迭代时使用获取每个元素的索引,并使用它来获取周围的项目.

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
Run Code Online (Sandbox Code Playgroud)