Need to split arrays to sub arrays of specified size in Ruby [duplicate]

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]]

Note: This question is not a duplicate of "How to chunk an array". The chunk question is asking about processing in batches and this question is about splitting arrays.


Solution 1:

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

Solution 2:

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]]

Solution 3:

If your using Rails 2.3+ you can do something like this:

arr.in_groups(3, false)

Checkout the api docs

Solution 4:

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]]