是否有内置的Ruby 1.8.7将数组拆分为相同大小的子数组?

Geo*_*Geo 5 ruby arrays

我已经开始了:

def split_array(array,size)
    index = 0
    results = []
    if size > 0
        while index <= array.size
            res = array[index,size]
            results << res if res.size != 0
            index += size
        end
    end
    return results
end
Run Code Online (Sandbox Code Playgroud)

如果我上运行它,[1,2,3,4,5,6]喜欢split_array([1,2,3,4,5,6],3)它会产生此阵:

[[1,2,3],[4,5,6]].在Ruby 1.8.7中是否有可以做到这一点的东西?

sep*_*p2k 10

[1,2,3,4,5,6].each_slice(3).to_a
#=> [[1, 2, 3], [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)

对于1.8.6:

require 'enumerator'
[1,2,3,4,5,6].enum_for(:each_slice, 3).to_a
Run Code Online (Sandbox Code Playgroud)