Read more

Split an array into groups

Henning Koch
February 01, 2011Software engineer at makandra GmbH

Given group size

If you would like to split a Ruby array into pairs of two, you can use the Rails ActiveSupport method in_groups_of Show archive.org snapshot :

>> [1, 2, 3, 4].in_groups_of(2)
=> [[1, 2], [3, 4]]

>> [1, 2, 3, 4, 5].in_groups_of(2)
=> [[1, 2], [3, 4], [5, nil]]

>> [1, 2, 3, 4, 5].in_groups_of(2, 'abc')
=> [[1, 2], [3, 4], [5, 'abc']]

>> [1, 2, 3, 4, 5].in_groups_of(2, false)
=> [[1, 2], [3, 4], [5]]

Given group count

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

If you would like to split a Ruby array into a given number of groups, you can use the Rails ActiveSupport method in_groups Show archive.org snapshot :

>> [1, 2, 3, 4, 5, 6].in_groups(2)
=> [[1, 2, 3], [4, 5, 6]]

>> [1, 2, 3, 4, 5, 6, 7].in_groups(2)
=> [[1, 2, 3, 4], [5, 6, 7, nil]]

>> [1, 2, 3, 4, 5, 6, 7].in_groups(2, 'abc')
=> [[1, 2, 3, 4], [5, 6, 7, 'abc']]

>> [1, 2, 3, 4, 5, 6, 7].in_groups(2, false)
=> [[1, 2, 3, 4], [5, 6, 7]]

Both in_groups_of and in_groups can also take a block that is yielded with each group.

Columns

If you would like to group arrays as “columns” where the first value lives in the first column, the second one in the second, etc. until it wraps, we have a note for that.

Posted by Henning Koch to makandra dev (2011-02-01 20:16)