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

时间:2010-02-02 20:17:39

标签: 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

如果我在[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中是否有可以做到这一点的东西?

1 个答案:

答案 0 :(得分:10)

[1,2,3,4,5,6].each_slice(3).to_a
#=> [[1, 2, 3], [4, 5, 6]]

对于1.8.6:

require 'enumerator'
[1,2,3,4,5,6].enum_for(:each_slice, 3).to_a
相关问题