tags:

views:

62

answers:

1

I've got this going:

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] like split_array([1,2,3,4,5,6],3) it will produce this array:

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

+7  A: 
[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
sepp2k
+1 Nice, you beat me to my answer. :-P
Chris Jester-Young
Thanks for the answer! However ... I'm stupid :). I actually have 1.8.6. Know anything for that as well?
Geo
Good answer. Alternative solution for Ruby 1.8.6 if to `require 'backports'` which will define `each_slice`.
Marc-André Lafortune