Split an array into groups

Updated . Posted . Visible to the public.

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

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.

Henning Koch
Last edit
Keywords
slice, list, collect, each
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-02-01 19:16)