Search code examples
ruby-on-railsrubyarraysruby-1.8.7

Dividing elements of a ruby array into an exact number of (nearly) equal-sized sub-arrays


I need a way to split an array in to an exact number of smaller arrays of roughly-equal size. Anyone have any method of doing this?

For instance

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 
groups = a.method_i_need(3)
groups.inspect
    => [[1,2,3,4,5], [6,7,8,9], [10,11,12,13]]

Note that this is an entirely separate problem from dividing an array into chunks, because a.each_slice(3).to_a would produce 5 groups (not 3, like we desire) and the final group may be a completely different size than the others:

[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13]]  # this is NOT desired here.

In this problem, the desired number of chunks is specified in advance, and the sizes of each chunk will differ by 1 at most.


Solution

  • You're looking for Enumerable#each_slice

    a = [0, 1, 2, 3, 4, 5, 6, 7]
    a.each_slice(3) # => #<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>
    a.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7]]