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

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

On Sun, Feb 13, 2011 at 12:16 PM, Gaba L.
[email protected] wrote:

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: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale