Although you could use Enumerator::each_slice as others have
suggested, it might be simpler to augment Array with a partition
function.
class Array
def partition(n, r=[])
raise ArgumentError if n <= 0
if n <= size then
r << first(n)
last(size - n).partition(n, r)
else
r << self unless empty?
return r
end
end
end
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(1) => [[1], [2], [3], [4],
[5], [6], [7], [8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(3) => [[1, 2, 3], [4, 5, 6],
[7, 8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(4) => [[1, 2, 3, 4], [5, 6, 7,
8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(6) => [[1, 2, 3, 4, 5, 6], [7,
8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(8) => [[1, 2, 3, 4, 5, 6, 7, 8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(10) => [[1, 2, 3, 4, 5, 6, 7, 8]]
p [ 1, 2, 3, 4, 5, 6, 7, 8 ].partition(-2) =>
untitled text:6:in `partition': ArgumentError (ArgumentError)
from untitled text:24
Hope this is helps.
Regards, Morton