ruby 将数组拆分为 m 大小的 n 组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7907368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:25:21  来源:igfitidea点击:

Split array up into n-groups of m size?

rubyarrays

提问by invaliduser

Possible Duplicate:
Need to split arrays to sub arrays of specified size in Ruby

可能的重复:
需要在 Ruby 中将数组拆分为指定大小的子数组

I'm looking to take an array---say [0,5,3,8,21,7,2] for example---and produce an array of arrays, split every so many places. If the above array were set to a, then

我正在寻找一个数组——例如 [0,5,3,8,21,7,2] 并生成一个数组数组,每隔这么多地方拆分。如果上面的数组被设置为a,那么

a.split_every(3)

would return [[0,5,3],[8,21,7][2]]

将返回 [[0,5,3],[8,21,7][2]]

Does this exist, or do I have to implement it myself?

这是否存在,还是我必须自己实现?

回答by Platinum Azure

Use Enumerable#each_slice.

使用Enumerable#each_slice.

a.each_slice(3).to_a

Or, to iterate (and not bother with keeping the array):

或者,迭代(而不是费心保留数组):

a.each_slice(3) do |x,y,z|
  p [x,y,z]
end

回答by maerics

a = (1..6).to_a
a.each_slice(2).to_a # => [[1, 2], [3, 4], [5, 6]]
a.each_slice(3).to_a # => [[1, 2, 3], [4, 5, 6]]
a.each_slice(4).to_a # => [[1, 2, 3, 4], [5, 6]]