Ruby’s #group_by method provides a way to (wait for it) group things by some arbitrary property. It’s part of the Enumerable module, so you can generally use it anywhere you’d be using #each or some iteration. To use #group_by, you first need to know two things:
The collection of objects that needs grouping (e.g., an array)
The rule by which you want to group those objects
#group_by returns a hash where the keys are defined by our grouping rule, and the values are the corresponding objects from our original collection.
Now let’s look at three examples of #group_by in action!
Example #1: Grouping strings
The collection: last names stored as strings in an array
The rule: group names according to the first letter
Example #2: Grouping integers
The collection: an array of 50 random integers between 1 and 99
The rule: group integers into 5 bins (e.g, 1-19, 20-39…)
Example #3: Grouping various objects
The collection: an array of various classes of objects
The rule: group objects by class
These are pretty contrived examples, but when combined with other methods, #group_by can be a handy way to get your objects in order. Now go get grouping!