我需要一种方法将一个数组分成粗略相等大小的确切数量的小数组。有人知道如何做到这一点吗?
例如:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
groups = a.method_i_need(3)
groups.inspect
=> [[1,2,3,4,5], [6,7,8,9], [10,11,12,13]]
在这个问题中,所需的块数事先指定,并且每个块的大小最多相差1。Note that this is an entirely separate problem from dividing an array into chunks, because
a.each_slice(3).to_a
would produce 5 groups (not 3, like we desire) and the final group may be a completely different size than the others:
[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13]] # this is NOT desired here.