Personal blog of Gunnari Auvinen. I enjoy writing about software engineering topics.

Picture of the author, Gunnari

Ruby Methods

June 8, 2014

There will come a time when you want to take the tangled collection of array values or hash values and organize them into neat little groups. Can you accomplish such a task with one method?

Examination of Enumerable#group_by

The work can be completed with the Enumerable method #group_by. This method will group the collection by the output of the block. #group_by returns, which has keys that are the output of the block, then each of those keys has an array of the values that correspond to that key. If that isn't particularly clear, don't worry the examples should help remove any confusion.

Examples

The first example that I'll use will show how you can use #group_by to group words in an array by their length.

['hi', 'bye', 'hello', 'cat', 'to', 'games', 'four', 'technology'].group_by { |word| word.length }

This will have the following result where the keys are the words length, and the values for each key will be an array of the words with that length.

{2=>["hi", "to"], 3=>["bye", "cat"], 5=>["hello", "games"], 4=>["four"], 10=>["technology"]}

This can be incredibly useful in many ways. #group_by can be used like it was in the example to obtain word length counts, it could group together numbers that have a similar property, it can be combined with other methods to find the most common element within an array or hash, and it can be used in other ways as well.

One interesting use of #group_by when it is combined with other methods is to find the most common element in an input array. For example you could find out the most common name in an array with the following code:

['Jon', 'Mary', 'Bob', 'Mary', 'Samantha'].group_by { |name| name }.values.max_by(&:size).first

This will return "Mary". First it groups the names together into arrays, then takes the largest element by size, and then returns the first value of that array. This can be used in situations such as counting votes and similar situations. There are many other uses that I didn't cover in these examples and I encourage you to take some time experimenting with this method. Please feel free to share any other uses you can think of with me, as I'd love to learn of more applications that I haven't thought of yet.

Closing Thoughts

When I first looked at #group_by I wasn't entirely certain how it could be used effectively, but as I examined it more, I came to see how it would be more useful than I originally understood. The more time that I spend with Ruby the more I think I'll run into more places where it could be used to great effect. I think it might be useful to use it to group people with administrator accounts and regular accounts, as well as figuring out who to send particular mailings. It will be exciting to see more uses for this method!