- Read Tutorial
- Watch Guide Video
This guide will walk through how to use grep
instead of other methods in Ruby, such as select
and map
to search through a collection.
To start with, I'm going to create an array of file names.
arr = ['hey.rb', 'there.rb', 'index.html']
Now let's see how we can use grep
to perform the functions of select
or map
.
First, let's say, you want to return only the files that end in the extension .rb
, and along with it, you want to remove the extension, so the output has only file names.
The typical code to implement this type of behavior would be something like:
p arr.select { |x| x=~ /\.rb/ }.map{ |x| x[0..-4]}
The output should have just the values ["hey", "there"]
.
Though that worked, we can make it more efficient by using the grep
method. By leveraging grep
our code can be consolidated down to:
arr.grep(/(.*)\.rb/){$1}
The output will be the same.
devCamp Note: The {$1}
is a tool that you can use regular expression matchers in Ruby to capture the values that were matched. So in our example the actual values that were matched were hey
and there
. The .rb
was left off by default because it was not part of the match value that was returned. Ruby borrowed this concept from the Perl programming language.