Split array up into n-groups of m size? [duplicate]
Possible Duplicate:
Need to split arrays to sub arrays of specified size in 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
a.split_every(3)
would return [[0,5,3],[8,21,7][2]]
Does this exist, or do I have to implement it myself?
Solution 1:
Use 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
Solution 2:
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]]