41

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.

bragboy
  • 34,892
  • 30
  • 114
  • 171
  • 1
    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. – Qwertie Jan 22 '19 at 05:32

4 Answers4

59
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
  • 363,768
  • 54
  • 674
  • 675
6

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]]
Nick Roz
  • 3,918
  • 2
  • 36
  • 57
4

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]]
JstRoRR
  • 3,693
  • 2
  • 19
  • 20
  • 1
    `array.group_by` is very useful. You can do the following: `false_group, true_group = some_array.group_by{|i| i.test_something?()}.values` – Automatico Oct 16 '14 at 13:32
3

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

arr.in_groups(3, false)

Checkout the api docs

Darren
  • 1,235
  • 1
  • 8
  • 2
  • 1
    This is wrong. It does not split an array to sub arrays of specified size, as author says. It creates 3 groups, bun not arrays of 3 – Nick Roz Jul 15 '16 at 13:37