I have an array
foo = %w(1 2 3 4 5 6 7 8 9 10)
How can I split or "chunk" this into smaller arrays?
cl开发者_开发知识库ass Array
def chunk(size)
# return array of arrays
end
end
foo.chunk(3)
# => [[1,2,3],[4,5,6],[7,8,9],[10]]
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
精彩评论