Using grep with Ruby

grep is a familiar Unix command that is also a method defined in the Enumerable module. The Enumerable module is included in the Array and Hash classes, which makes the grep method accessible.

Here is how to use grep() to select all elements from this array [“mat”, “lat”, “cat”, “cool”, “dude”, “fat”] with the letters “at”:

["mat", "lat", "cat", "cool", "dude", "fat"].grep(/at/)

The select() method can also be used to arrive at the same result, but the syntax is more complicated:

["mat", "lat", "cat", "cool", "dude", "fat"].select{|word| word.include?("at")}

A block can also be passed to the grep method. Suppose you have a people = [“Matt P.”, “Cat P.”, “Lat S.”, “Joe L.”] array and would like to find every person with “P.” as a last name and replace it with Powers. The desired result is [“Matt Powers”, “Cat Powers”].

p = ["Matt P.", "Cat P.", "Lat S.", "Joe L."]
p.grep(/P./) {|name| name.sub(".", "owers") }

Passing a block to the grep method is very similar to using the map() method, but slightly more concise:

p.grep(/P./).map {|name| name.sub(".", "owers") }

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s