- Read Tutorial
- Watch Guide Video
In this guide we are going to learn more about a powerful method in Ruby called grep. This method is used to easily search through arrays and other collections.
We are going to learn the use of this method in a real world Rails application.
If I go to the root of the application in the terminal I can run the command rake routes
to get a list of all routes in the application.
This will display all the different routes in the application, like this:
This is helpful but it's also a bit overwhelming, what if I wanted only the routes specific to posts
? To filter this list I can use the grep
method. If I run the following command in the terminal:
rake routes | grep posts
The output will be much more manageable.
When you use this command, it only brings up all the routes that have the word posts
in them.
So, what is grep
doing exactly?
Let's see a simple example:
arr = [1, 3, 2, 12, 1, 2, 3] p arr.grep(1)
In this code we have a basic array of integers. From here we're calling the grep
method on the array and passing in the value that we want to search for, in this case it's 1
. The output will be an array containing the two instances of 1
.
[1, 1]
Now, if you search for 100
with the code, grep(100)
, it will return an empty array because there are no array elements of 100
.
So, grep
is an elegant and easy way to search through collections. Keep in mind you wouldn't use grep
to search through a database or anything of that size since you'd run into performance issues, however it's great for smaller collections.