Is there a built-in Ruby 1.8.7 for splitting an array into the same dimensional subarrays?

I managed:

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

If I run it on [1,2,3,4,5,6], for example split_array([1,2,3,4,5,6],3), it will create this array:

[[1,2,3],[4,5,6]]. Is there something already available that can be done in Ruby 1.8.7?

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

For 1.8.6:

require 'enumerator'
[1,2,3,4,5,6].enum_for(:each_slice, 3).to_a
+10
source

All Articles