grep and scan regular expressions in ruby

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.

{% codeblock lang:ruby %}

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

{% endcodeblock %}

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.

{% codeblock lang:ruby %}

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

{% endcodeblock %}

Code for grep method.

{% codeblock lang:ruby %}

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."]

{% endcodeblock %}

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 powered by Disqus