22
votes

Both of these methods sound like they should do the same thing but they don't appear to be aliases of each other. What is the difference between in_groups and in_groups_of?

1
One is basically slice, the other puts them in even-sized groups. Got it. - BookOfGreg
Another way to think of it: in_groups(n) returns a 2D array with n rows, whereas in_groups_of(n) returns a 2D array with n columns. - Stefan

1 Answers

44
votes

The documentation is quite clear.

in_groups(number, fill_with = nil)

Splits or iterates over the array in number of groups, padding any remaining slots with fill_with unless it is false.

in_groups_of(number, fill_with = nil)

Splits or iterates over the array in groups of size number, padding any remaining slots with fill_with unless it is false.

Example:

# Splits in groups of 2
["a","b","c","d","e","f"].in_groups_of(2)
# => [["a", "b"], ["c", "d"], ["e", "f"]]

# Splits in 2 groups
["a","b","c","d","e","f"].in_groups(2)
# => [["a", "b", "c"], ["d", "e", "f"]]