现在,这是数组,
[1,2,3,4,5,6,7,8,9]
我要,
[1,2],[2,3],[3,4] upto [8,9]
当我这样做时,我得到 each_slice(2),
[[1,2],[3,4]..[8,9]]
我目前正在做这个,
arr.each_with_index do |i,j|
p [i,arr[j+1]].compact #During your arr.size is a odd number, remove nil.
end
有没有更好的办法??
最佳答案
Ruby 会读懂你的想法。您想要cons 执行要素吗?
[1, 2, 3, 4, 5, 6, 7, 8, 9].each_cons(2).to_a
# => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9]]
关于Ruby 数组一次访问 2 个连续(链接)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15682223/