我有一个数组
foo = %w(1 2 3 4 5 6 7 8 9 10)
如何将其拆分或“分块”成更小的数组?
class Array def chunk(size) # return array of arrays end end foo.chunk(3) # => [[1,2,3],[4,5,6],[7,8,9],[10]]
看看Enumerable#each_slice:
foo.each_slice(3).to_a #=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]