0

Say I build an array like this:

:001 > holder = "This.File.Q99P84.Is.Awesome"
=> "This.File.Q99P84.Is.Awesome" 
:002 > name = holder.split(".")
=> ["This", "File", "Q99P84", "Is", "Awesome"]

Now, I can do:

name[2].include? 'Q99P84' 

Instead of putting in 'Q99P84' I want to put in something like 'symbol for Q followed by symbol for number, symbol for number, symbol for P, symbol for number, symbol for number
so the .include? function will be dynamic. So any file name I load that has Q##P## will return true.

I'm pretty sure this is possibly I just don't know exactly what to search. If you know the answer can you link me to the documentation.

1
  • 3
    this is called "regular expressions". Try to google them. Commented Jun 21, 2013 at 15:07

2 Answers 2

3

What you're looking for is regular expression matching. The Ruby regexp object will help you. What you want is something like

/Q[\d+]P[\d+]/.match(name[2])

...which will return a truthy value if name[2] has a string which matches a character Q, one or more digits (0-9), a character P, then one or more digits. This is probably too flexible a match if the pattern you want has exactly two digits in those number spaces; for that you might try a more specific pattern:

/Q\d\dP\d\d/.match(name[2])
0

One way to do this is through Regular Expressions ('regex' for short). Two good sources of information is Regular Expression.info and Rubular which is more Ruby centric.

One way to use regex on a string is the String#match method:

names[2].match(/Q\d\dP\d\d/) # /d stands for digit 

This will return the string if there is a match and it will return nil if there isn't.

"Q42P67".match(/Q\d\dP\d\d/) #=> "Q42P67"
"H33P55".match(/Q\d\dP\d\d/) #=> nil

This is helpful in an if condition since a returned string is 'truthy' and nil is 'falsely'.

names[2] = "Q42P67"
if names[2].match(/Q\d\dP\d\d/)
   # Will execute code here
end

names[2] = "H33P55"
if names[2].match(/Q\d\dP\d\d/)
   # Will not execute code here
end

I hope that helps until you dig further into your study of Regular Expressions.

EDIT: Note that the Q and P in /Q\d\dP\d\d/ are capital letters. If case is not important, you can append an 'i' for case-insensitivity. /Q\d\dP\d\d/i will capture "Q42P67" and "q42P67"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.