bragboy bragboy - 4 months ago 9
Ruby Question

Need to split arrays to sub arrays of specified size in Ruby

I have an array that is 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 the following:
[[4, 5, 6], [7,8,4], [45,11]]

Answer
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
Comments