How does this line of code work? (it's simple)

G

Gaba Luschi

x = "This is a test".match(/(\w+) (\w+)/)
Why does puts x[0] give you "THis is"
and puts x[1] give you "This"

etc?

Thanks
 
R

Rick DeNatale

x = "This is a test".match(/(\w+) (\w+)/)
Why does puts x[0] give you "THis is"
and puts x[1] give you "This"

etc?

The regular expression:

/(\w+) (\w+)/

has two capture groups (the stuff in the parentheses). The first
capture group matches the first word (actually the first run of one or
more word characters) in the string, the regex then wants a single
blank and then the second capture group matches the second word.

Now the expression

"This is a test".match(/(w+) (w+)/

Evaluates to an instance of MatchData, and a MatchData acts like a
pseudo array where the 0th element returns what the whole regexp
matched, and the nth element (for n>0) returns what the nth capture
group matched.

Note that your regular expression isn't anchored so the first word
doesn't need to come tat the beginning of the string:

x = "%^&* darn rabbit".match(/(\w+) (\w+)/) => #<MatchData "darn
rabbit" 1:"darn" 2:"rabbit">

x[0] => "darn rabbit"
x[1] => "darn"
x[2] => "rabbit"

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: http://github.com/rubyredrick
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,522
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top