Iacutone.rb

coding and things

Grep and Scan Methods With Regular Expressions in Ruby

| Comments

I am creating an app to provide food cart locations in Manhattan. Here is the code. Food carts generally post their locations on Twitter; in order to create latitude and longitude coordinates, I needed to parse tweets. This is where scan and grep play their role, to match elements in a tweet string. Let's say this is our tweet: "53rd and park. Ready by 11!" This string is database column in my locations model.

Code for scan method.

1
2
3
4
5
 tweet = "53rd and park. Ready by 11!"
  tweet.scan(/53/)
  # => ["53"] 
  tweet.scan(/Park/i)
  # => ["park"]

The scan method takes a string as an input. Also, the i is used in the regular expression in order to make it case insensitive.

1
2
 tweet.scan(/Park/)
  #  => [] 

Code for grep method.

1
2
3
4
5
6
7
 tweet = "53rd and park. Ready by 11!"
  tweet_array = tweet.split
  # => ["53rd", "and", "park.", "Ready", "by", "11!"] 
  tweet_array.grep(/53/)
  # => ["53rd"]
  tweet_array.grep(/Park/i)
  # => ["park."]

The grep method takes an array as an input, so use the string split method to turn it into an array seperated by commas. Also, the regular expression matches the entire string. The grep method seems to be more suited as an alternative for the select and map methods. This blog post goes into further detail explaining more cases to use the grep method over more familiar methods.

Comments