Quantcast
Channel: Programming – PMA Media Group
Viewing all articles
Browse latest Browse all 10

The Scan() Method for Regular Expressions

$
0
0

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.


Viewing all articles
Browse latest Browse all 10

Trending Articles