我有一个大型数组,我想将其均匀地分成n个数组.
我尝试使用each_slice,但只根据传递给它的数字参数将数组切成小部分.
我怎样才能做到这一点?
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.group_by.with_index{|_, i| i % 2}.values
# => [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
a.group_by.with_index{|_, i| i % 3}.values
# => [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]
a.group_by.with_index{|_, i| i % 4}.values
# => [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]
a.group_by.with_index{|_, i| i % 5}.values
# => [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
a.group_by.with_index{|_, i| i % 6}.values
# => [[1, 7], [2, 8], [3, 9], [4, 10], [5], [6]]
Run Code Online (Sandbox Code Playgroud)