Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between rails in_groups and in_groups_of?

Tags:

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?

  • Array#in_groups
  • Array#in_groups_of
like image 447
BookOfGreg Avatar asked Aug 18 '15 12:08

BookOfGreg


1 Answers

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"]] 
like image 92
gernberg Avatar answered Oct 13 '22 02:10

gernberg