More balanced array manipulation than each_slice?

I have an array of 10 elements, and I want to split it into 3 sections that look like this:

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

Using each_slice , I can get closer:

 a = *(1..10) a.each_slice(4) # use 4 so I can fit everything into 3 sections [1, 2, 3, 4] [5, 6, 7, 8] [9, 10] 

But I want the first format to be more evenly distributed. I can do this by writing my own method. But is there a built-in way to do this in ruby ​​1.9+?

Update:

Since there is no built-in way, I would like to change my question to , how would you implement it?

+4
source share
1 answer

Here is my implementation

  def chunk(a, pieces) size = a.size / pieces extra = a.size % pieces chunks = [] start = 0 1.upto(pieces) do |i| last = (i <= extra) ? size.next : size chunks << a.slice(start, last) start = chunks.flatten.size end chunks end 

name it like that

 a = *(1..10) puts chunk(a, 3) 

displays

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

If the part size is too large, it fills the empty arrays

 a = *(1..10) puts chunk(a, 14) 

displays

 [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [], [], [], []] 
+3
source

All Articles