拆分阵列成M尺寸的正团? [英] Split array up into n-groups of m size?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/3864139/need-to-split-arrays-to-sub-arrays-of-specified-size-in-ruby\">Need拆分阵列指定大小的子阵列中的Ruby
我希望利用阵列---例如说[0,5,3,8,21,7,2] ---并产生一个数组的数组,每个分割这么多的地方。如果上述阵列被设置为一个,然后
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
a.split_every(3)
将返回[[0,5,3],[8,21,7] [2]
would return [[0,5,3],[8,21,7][2]]
这是否存在,还是我要实现它自己?
Does this exist, or do I have to implement it myself?
推荐答案
使用<一个href=\"http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-each_slice\"><$c$c>Enumerable#each_slice$c$c>.
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
这篇关于拆分阵列成M尺寸的正团?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!