Today I Learned

hashrocket A Hashrocket project

Grepping in Ruby

I was looking at a rather large model in Ruby and wanted to search through its methods to see what might be available. I found out there's an Enumerable#grep method that lets you search like you would in the terminal.

Here's a simple example:

["apple", "banana", "apricot"].grep(/^ap/)
# => ["apple", "apricot"]

Here's some more useful examples:

[1, "two", :three].grep(String)
# => ["two"]

[3, 7, 12].grep(1..10)
# => [3, 7]

Here's a real world example I used it for:

Post.methods.grep(/deleted/)
=> [:without_deleted, :with_deleted, :deleted, :only_deleted]
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.