Using grep in Ruby

Most users of POSIX based systems have most likely heard of or use the grep command regularly. For those who don’t know, grep is a method of searching an input file for a match of one or more patterns. It’s a very useful and powerful tool, especially when you pair it with some advanced regular expressions.

One of the things I didn’t know until yesterday, and thought would be interesting to share, is that you can also use grep on any Ruby class that includes the Enumerable module.

The output of ri Enumerable#grep is as follows:

This means that we can do some seriously powerful and specific searches for elements within any Enumaerble using regular expressions.

One of the things that isn’t mentioned explicity in the ri documentation is that you can also grep on module and class types, too:

Whenever you grep for a specific class, it returns an array of the elements within the Enumerable that matches said class, or an empty array if there are no matches.

It also works across the class hierarchy, e.g.

Grepping against modules is also supported, and works how you would imagine — matching any classes that include the module given:

If you would like to be more specific and find a certain element in an Enumerable, grep allows you to do it:

Interestingly, grep is only a smidge faster than select in the benchmark I ran below ran using ruby 2.4.1p111.

Keep in mind, in the real world, the speed difference most likely won’t matter, just use the one that is easier to read for you and your team.

Grepping, whether in a POSIX system’s command line, or in Ruby, is a great and powerful tool. This power is supercharged with the use of regular expressions and, in Ruby, grepping against an enumerable’s children’s class, or module types can prove to be a great way to make potentially complex searches easier to read.

Thanks to Pericles Theodorou for the enlightenment.

Edited on 30th of June to update the benchmark to use a more accurate comparison, thanks to @sgrif.

Interested in making an Impact? Join the carwow team!
Feeling social? Connect with us on Twitter and LinkedIn :-)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store