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

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

can also utilize this with a specific purpose:

((1..10).group_by {|i| i%3}).values    #=> [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

in case you just want two partitioned arrays:

(1..6).partition {|v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]]

In Rails you can use method in_groups_of which splits an array into groups of specified size

arr.in_groups_of(3) # => [[4, 5, 6], [7, 8, 4], [45, 11, nil]]
arr.in_groups_of(3, false) # => [[4, 5, 6], [7, 8, 4], [45, 11]]

Whereas method in_groups splits an array into specified number of balanced groups

arr.in_groups(5) # => [[4, 5], [6, 7], [8, 4], [45, nil], [11, nil]]
arr.in_groups(5, false) # => [[4, 5], [6, 7], [8, 4], [45], [11]]

Tags:

Arrays

Ruby