Possible Duplicate:
Need to split arrays to sub arrays of specified size in Ruby
What is the best way to segment an array by a given length? What I want is something like 'segment_by' in the following:
[1, 2, 3, 4, 5, 6].segment_by(2)
# => [[1, 2], [3, 4], [5, 6]]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].segment_by(3)
# => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
What I managed to come up with is the following, but it looks not simple enough:
class Array
def segment_by i
(0...length).group_by{|x| x.div(i)}.values.map{|a| a.map{|j| self[j]}}
end
end
I am using ruby1.9.2. Is there already such method, and it there a better way to do it?