我如何在迭代数组时从数组中获取当前元素的下一个和之前的数据.
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)
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)
| 归档时间: |
|
| 查看次数: |
9995 次 |
| 最近记录: |