现在,这是阵列,[1,2,3,4,5,6,7,8,9]我想要,[1,2],[2,3],[3,4] upto [8,9]当我这样做时,每个我都得到了(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有没有更好的办法??
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
你几乎做对了:)
arr = [1,2,3,4,5,6,7,8,9]
arr.each_cons(2) do |chunk|
p chunk
end
# >> [1, 2]
# >> [2, 3]
# >> [3, 4]
# >> [4, 5]
# >> [5, 6]
# >> [6, 7]
# >> [7, 8]
# >> [8, 9]
- 3 回答
- 0 关注
- 541 浏览
添加回答
举报
0/150
提交
取消