Split array up into n-groups of m size?

RubyArrays

Ruby Problem Overview


> 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?

Ruby Solutions


Solution 1 - Ruby

Use http://www.ruby-doc.org/core-1.9.2/Enumerable.html#method-i-each_slice">`Enumerable#each_slice`</a>;.

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 - Ruby

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]]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninvaliduserView Question on Stackoverflow
Solution 1 - RubyPlatinum AzureView Answer on Stackoverflow
Solution 2 - RubymaericsView Answer on Stackoverflow