What is the difference between rails in_groups and in_groups_of?

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?

2

1 Answer

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"]]

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like