tags:

views:

42

answers:

1

Hi,

I have an array something like this,

arr = [4, 5, 6, 7, 8, 4, 45, 11]

I want a fancy method like

sub_arrays = split (arr, 3)

This should return me [[4, 5, 6], [7,8,4], [45,11]]

+3  A: 
arr.each_slice(3).to_a

each_slice returns an Enumerable, so if that's enough for you, you don't need to call to_a.

In 1.8.6 you need to do:

require 'enumerator'
arr.enum_for(:each_slice, 3).to_a

If you just need to iterate, you can simply do:

arr.each_slice(3) do |x,y,z|
  puts(x+y+z)
end
sepp2k
Thanks! that was really fast!
Bragboy
Or `b=[]; b << a.shift(3) until a.empty?` (for old Rubys)
Nakilon
@Nakilon: That will destroy the original array though.
sepp2k
@sepp2k, oops, yes, need more code. `c,b=a.dup,[]; b << c.shift(3) until c.empty?`. And can be problems with `dup` if `a` isn't a 1-dimensioanl array etc.
Nakilon