# use as standalone function def chunk_array(array, pieces=2) len = array.length; mid = (len/pieces) chunks = [] start = 0 1.upto(pieces) do |i| last = start+mid last = last-1 unless len%pieces >= i chunks << array[start..last] || [] start = last+1 end chunks end # use as array.chunk class Array def chunk(pieces=2) len = self.length; mid = (len/pieces) chunks = [] start = 0 1.upto(pieces) do |i| last = start+mid last = last-1 unless len%pieces >= i chunks << self[start..last] || [] start = last+1 end chunks end end
Examples of use:
>> chunk_array [1,2,3,4,5,6], 2 => [[1, 2, 3], [4, 5, 6]] >> chunk_array [1,2,3,4,5,6], 3 => [[1, 2], [3, 4], [5, 6]] >> chunk_array [1,2,3,4,5,6], 4 => [[1, 2], [3, 4], [5], [6]] >> chunk_array [1,2,3,4,5,6,7,8,9,10], 4 => [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]] >> chunk_array [1,2,3], 4 => [[1], [2], [3], []] >> chunk_array [], 2 => [[], []]
if you prefer the second form (more ruby-ish, but not always appropriate)
>> [1,2,3,4,5,6,7,8,9,10].chunk => [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] >> [1,2,3,4,5,6,7,8,9,10].chunk 3 => [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
This is handy when used with a splat because you can do things like:
left, right = *chunk_array(all,2)
class Array
def / len
a = []
each_with_index do |x,i|
a << [] if i % len == 0
a.last << x
end
a
end
end
[:now, :is, :the, :time, :for, :all, :good, :men, :to, :come, :to, :the, :aid] / 3
gives
=> [[:now, :is, :the], [:time, :for, :all], [:good, :men, :to], [:come, :to, :the], [:aid]]