我有一个阵列
foo = %w(1 2 3 4 5 6 7 8 9 10)
Run Code Online (Sandbox Code Playgroud)
如何将其拆分或"分块"为更小的数组?
class Array
def chunk(size)
# return array of arrays
end
end
foo.chunk(3)
# => [[1,2,3],[4,5,6],[7,8,9],[10]]
Run Code Online (Sandbox Code Playgroud) 我需要一种方法将数组拆分为另一个大小相等的数组中的一堆数组.有人有任何方法吗?
例如
a = [0, 1, 2, 3, 4, 5, 6, 7]
a.method_i_need(3)
a.inspect
=> [[0,1,2], [3,4,5], [6,7]]
Run Code Online (Sandbox Code Playgroud) 我有一个类似这样的数组:
arr = [4, 5, 6, 7, 8, 4, 45, 11]
Run Code Online (Sandbox Code Playgroud)
我想要一种奇特的方法
sub_arrays = split (arr, 3)
Run Code Online (Sandbox Code Playgroud)
这应该返回以下内容: [[4, 5, 6], [7,8,4], [45,11]]
Note: This question is not a duplicate of "How to chunk an array" The chunk question is asking about processing in batches and this question is about splitting arrays.
我有一个大型数组,我想将其均匀地分成n个数组.
我尝试使用each_slice,但只根据传递给它的数字参数将数组切成小部分.
我怎样才能做到这一点?