Unique Marketing, Guaranteed Results.

The Scan() Method for Regular Expressions

June 16th, 2009 by Chris Gunnels

As I was writing a simple script to display the education I received from reading The Ruby Way 2nd Edition chapters 2 and 3, I found a really neat method that helped me complete my task. If you didn’t read the title of this blog post then your out of luck, but if you read the title then you will know that I am talking about the scan() method.

Back to my script, since I wanted to find the number of occurrences white space showed up in a given string I had to come up with a way to count white space. My first thought was to do some regular expression matching. Well after a little thought and a lot of reading, I found a this:


answer = params[:string].scan(/(\s)/)
puts answer.size

Here’s a little breakdown of whats happening for those that don’t know.

GIVEN: params is a hash with the values that were posted via a form.
Line 1: we are running the scan method on params[:string] which the value is a string. Then we pass scan method a regular expression that looks for any white space. Then the value of that is assigned to the local answer variable.
Line 2: we print the answer’s size.

Filed under: Programming — Tags: , , , , , — Chris Gunnels @ 12:59 pm on June 16, 2009

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Copyright © 2005-2016 PMA Media Group. All Rights Reserved &nbsp