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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)