How to Use the Ruby Grep Method (With Examples)

Let’s talk about the grep method.

What can this method do for you?

You can use Grep to filter enumerable objects, like Arrays & Ranges.

“But select already does that!”

Yes, but grep works in a different way & it produces different results.

Let’s see some examples.

Ruby Grep Method Examples

Given this array:

objects = ["a", "b", "c", 1, 2, 3, nil]

You can use grep to get only the strings:

# ["a", "b", "c"]

Only the Integers:

# [1, 2, 3]

Or everything that isn’t nil:

# ["a", "b", "c", 1, 2, 3]

If you have an array of words:

fruit = ["apple", "orange", "banana"]

You can find all the words that start with “a”:

# ["apple"]

Or that end with “e”:

# ["apple", "orange"]

And if you have a list of numbers:

numbers = [9, 10, 11, 20]

You can get a list of all the numbers within a range:

# [9, 10]

You can combine the map method & select into one when you use a block:

numbers.grep(5..10) { |n| n * 2 }
# [18, 20]

If you want to get fancy…

times_two = ->(x) { x * 2 }

numbers.grep(5..10, &times_two)
# [18, 20]

Pretty cool, right?

Grep vs Select: Understanding The Difference

How does grep work?

The trick is with the === method (triple equals) in Ruby.

Grep calls this method on whatever argument you pass to it.

And it turns out that classes, regular expressions & ranges all implement ===.

They implement this method in a way that makes sense for the class.

For example:

  • Classes (like Integer or Array), compare with the given object class.
  • Ranges check if the number is included in the range.
  • Regular expressions check if there is a match.

So when you say:


What you’re really saying is: { |obj| Integer === obj }

For a long time, I was confused about grep…

Until I understood this.

The select method filters a list based on the results of the block.

If the block evaluates to true, then that element gets chosen.

But grep just compares two things using ===.

You could say that grep is a more specialized version of select!

Ruby Grep Mindmap

Grep Mindmap

Watch Video Tutorial


You learned about the grep method in Ruby! It’s a very helpful method when you understand how it works.

Make sure to practice to let this sink in.

Practice is the key to mastery!

cathy says a couple of years ago

Nice Article.. Thanks!

    Jesus Castello says a couple of years ago

    Thanks for reading! 🙂

Mitch says a couple of years ago

Thanks for putting this together and for explaining the differences/similarities between grep and select!

    Jesus Castello says a couple of years ago

    Thanks for your comment! I’m glad you found this useful 🙂

Serguei says a couple of years ago

Very cool features I’ve never heard before, thank you for very much, Jesus, for sharing !

Rocela says a couple of years ago

The grep_v method was added only in Ruby 2.3.

An alternative is to use the compact method in the array.

Comments are closed