Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > How does this line of code work? (it's simple)

Thread Tools

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

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



Posted via

Reply With Quote
Rick DeNatale
Posts: n/a
On Sun, Feb 13, 2011 at 12:16 PM, Gaba Luschi
<(E-Mail Removed)> 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

Twitter: @RickDeNatale

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
Read a file line by line and write each line to a file based on the5th byte scad C++ 23 05-17-2009 06:11 PM
How to read a text file line by line and remove some line kaushikshome C++ 4 09-10-2006 10:12 PM
Beginner: read $array with line breaks line by line Marek Stepanek Perl Misc 12 09-02-2006 10:27 AM
Read a file line by line with a maximum number of characters per line Hugo Java 10 10-18-2004 11:42 AM