PDA

View Full Version : Ruby method help



John Basedow
22nd February 2008, 12:06 PM
I'm taking a course that teaches us the basics of Ruby, but has its focus more on what we can do with Ruby to aid linguistic study.

Right now, I'm still trying to master how regular expressions interact with the method calls in this language, and any help is appreciated. I posted this in S/C too, but I figure it'd get more serious replies here.

I'm having trouble with a program in Ruby that searches lines for valid email addresses. I'm using a method in the language called "aVariable.scan(/regexp/) (replace "regexp" with the regular expression for valid emails, and "aVariable" with any string). ".scan" will iterate through each line of standard input, and match the regular expression to instances within the string, and assign it to an array. If you have parenthetical sub-divisions within that regular expression (example: /(\w+\.)+/) it will assign each parenthesis to a different item in the array. So if I were to feed the .scan method this regular expression:

line.scan(/(\w+\.)+@(\w+\.)+com|net|org|mil/)

and then have the program return the value(s) it scanned, it would give me stuff like:

Input: monkey.zebra.giraffe@yahoo.monkey.com
monkey.
monkey.
com

Now, I thought about creating an entirely new class where each variable would have space for "prefixes" "ats" "suffixes" and "domains." Problem is, each iteration would require a new variable to be created.

Update: Figured it out. I needed a special character to make sure the parentheses didn't "capture."

line.scan(?:/(\w+\.)+@(?:\w+\.)+com|net|org|mil/)