Ruby数组一次访问2个连续的(链式)元素 [英] Ruby array access 2 consecutive(chained) elements at a time
本文介绍了Ruby数组一次访问2个连续的(链式)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,这是数组,
[1,2,3,4,5,6,7,8,9]
我想要
[1,2],[2,3],[3,4] upto [8,9]
当我这样做时,我得到了each_slice(2)
When I do, each_slice(2) I get,
[[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读懂了你的想法.您要缺点执行元素吗?
Ruby reads your mind. You want cons ecutive elements?
[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个连续的(链式)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文