Q:

Splitting an array into x arrays

I have an array:
arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to split arr1 into x slices, where each slice is as full and equal as possible. 
arr2  = arr1.foo(3)
# => [1, 2, 3, 4][5, 6, 7][8, 9, 10]

each_slice does the opposite of what I want, separating the array into groups of x elements instead. 
arr2 = arr1.each_slice(3)
# => [1, 2, 3][4, 5, 6][7, 8, 9][10]

If possible, I want to do this without using rails-specific methods like in_groups. 

A:

class Array
  def in_groups(n)
    len, rem = count.divmod(n)
    (0...n).map { | i | (i < rem) ?  self[(len+1) * i, len + 1] : self[len * i + rem, len] }
  end
end

A:

Another approach:
def in_groups(array, n)
  a = array.dup
  n.downto(1).map { |i| a.pop(a.size / i) }.reverse
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

in_groups(arr, 1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
in_groups(arr, 2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
in_groups(arr, 3) #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
in_groups(arr, 4) #=> [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]
in_groups(arr, 5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

A:

You could use recursion:
def in_groups(arr, n)
  return [arr] if n == 1
  len = arr.size/n
  [arr[0,len]].concat in_groups(arr[len..-1], n-1)
end

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

in_groups(arr,  1) #=> [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] 
in_groups(arr,  2) #=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] 
in_groups(arr,  3) #=> [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] 
in_groups(arr,  4) #=> [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]] 
in_groups(arr,  5) #=> [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] 
in_groups(arr,  9) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9, 10]] 
in_groups(arr, 10) #=> [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] 
in_groups(arr, 11) #=> [[], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]] 

Edit 1: For largest groups first, tack on .reverse or replace the antepenultimate line with:
len = (arr.size.to_f/n).ceil

Edit 2: the following is a slight variant of @undur's answer, possibly easier to follow for those with brain types "B" and "C":
class Array
  def in_groups(n)
    size_small, nbr_large = count.divmod(n)
    size_large, nbr_small = size_small+1, n-nbr_large
    nbr_for_large = nbr_large * size_large  
    self[0, nbr_for_large].each_slice(size_large).to_a.concat(
      self[nbr_for_large..-1].each_slice(size_small).to_a)
  end
end

(1..10).to_a.in_groups(3)
  #=> [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] 

