Save That Potluck with Group_By!

When you host a potluck, whatss the biggest problem. Too much food? Possibly. Too many guests? Possibly. Everyone signing up to bring napkins? Definitely.

Since coding is used to solve critical everyday problems such as having too many napkins at a potluck (because we all know this leads to a shortage of food!), we can use the Enumerable method group_by to help us quickly sort our potluck list for the surplus of napkin-bringers. But first…a little background on Enumerable.

In Ruby, there's something called the Enumerable module which provides a set of methods that search, sort, navigate, and manipulate collections in a readable and terse manner. Enumerable is possible in Ruby because of the concept of 'mixins'. Unlike some languages which permit code sharing only through inheritance - often limited to one parent class - Ruby has modules to contain various methods. So, if you want to write code once and share it amongst many classes, you can use modules to be 'mixed in' with your classes.

Since pertaining to collections, a class using Enumerable must define an #each method that yields each item in the collection to a block. Essentially Enumerables are a different way of implementing the concepts of loops, arrays, and hashes.

To find out which classes use Enumerable, use 'Object#included_modules', where Object can be Array, String, Float, etc. To see all the methods provided by Enumerable, you can check the output of #instance_methods below.

Ok, so back to our napkin method…or 'group_by': group_by { | obj | block } -> a_hash.

A couple examples before we catch our napkin-bringers. As seen in the simple example above, we passed the numbers 1 - 10 be evaluated through the expression 'num%3'. The result is a hash where the keys are the remainder values '0,1,2' and values those nums that 'caused' the respective remainder values.

The returning keys don’t have to be the same data type as the values in the array either:

And finally, let's find out if we'll be eating napkins for dinner:

All in all, it's a great way to sort collections of data into neat groups.

References: