Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
给定这个 Ruby 数组:
[1, 2, 3, 4, 5]
像这样迭代它的最简单方法是什么?
[[1,2], [2,3], [3,4], [4,5]]
或这个?
[[1,2,3], [2,3,4], [3,4,5]]
each_cons(文档)这样做。您只需将所需块的大小传递给它,它就会将它们交给您传递的块。
each_cons
如果你真的想要数组,那么你当然可以用 链接它to_a,例如
to_a
(1..5).each_cons(3).to_a