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.
我需要以指定大小的块反转数组。这是需要发生的事情的示例:
chunk = 2 arr = [1,2,3,4,5]
如何构建一个数组,其中块被反转如下:
[2, 1, 4, 3, 5]
我的代码:
arr.each_slice(chunk) { |a| p a }
输出:
[1,2] [3,4] [5]
上面的每个块都需要反转并附加到最终数组,如上所示。
arr = [1,2,3,4,5] arr.each_slice(2).flat_map(&:reverse) # => [2, 1, 4, 3, 5]