如何迭代ruby数组并始终获得两个值,即当前和下一个,如:
[1,2,3,4,5,6].pairwise do |a,b|
# a=1, b=2 in first iteration
# a=2, b=3 in second iteration
# a=3, b=4 in third iteration
# ...
# a=5, b=6 in last iteration
end
我的用例:我想测试数组是否已排序,并且通过使用这样的迭代器,我总能比较两个值。
我不是在这个问题中搜索each_slice
:Converting ruby array to array of consecutive pairs
答案 0 :(得分:29)
您正在寻找each_cons
:
(1..6).each_cons(2) { |a, b| p a: a, b: b }
# {:a=>1, :b=>2}
# {:a=>2, :b=>3}
# {:a=>3, :b=>4}
# {:a=>4, :b=>5}
# {:a=>5, :b=>6}