This question already has an answer here:
- How to chunk an array in Ruby 2 answers
I need a way to split an array in to a bunch of arrays within another array of equal size. Anyone have any method of doing this?
For instance
a = [0, 1, 2, 3, 4, 5, 6, 7]
a.method_i_need(3)
a.inspect
=> [[0,1,2], [3,4,5], [6,7]]
Try
It will do your job
You're looking for
Enumerable#each_slice
As mltsy wrote,
in_groups(n, false)
should do the job.I just wanted to add a small trick to get the right balance
my_array.in_group(my_array.size.quo(max_size).ceil, false)
.Here is an example to illustrate that trick:
Perhaps I'm misreading the question since the other answer is already accepted, but it sounded like you wanted to split the array in to 3 equal groups, regardless of the size of each group, rather than split it into N groups of 3 as the previous answers do. If that's what you're looking for, Rails (ActiveSupport) also has a method called in_groups:
I don't think there is a ruby equivalent, however, you can get roughly the same results by adding this simple method:
The only difference (as you can see) is that this won't spread the "empty space" across all the groups; every group but the last is equal in size, and the last group always holds the remainder plus all the "empty space".
Update: As @rimsky astutely pointed out, the above method will not always result in the correct number of groups (sometimes it will create multiple "empty groups" at the end, and leave them out). Here's an updated version, pared down from ActiveSupport's definition which spreads the extras out to fill the requested number of groups.
This needs some better cleverness to smear out the extra pieces, but it's a reasonable start.