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

Discussion in 'Ruby' started by Gaba Luschi, Feb 13, 2011.

  1. Gaba Luschi

    Gaba Luschi Guest

    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

    --
    Posted via http://www.ruby-forum.com/.
     
    Gaba Luschi, Feb 13, 2011
    #1
    1. Advertising

  2. On Sun, Feb 13, 2011 at 12:16 PM, Gaba Luschi
    <> 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: http://github.com/rubyredrick
    Twitter: @RickDeNatale
    WWR: http://www.workingwithrails.com/person/9021-rick-denatale
    LinkedIn: http://www.linkedin.com/in/rickdenatale
     
    Rick DeNatale, Feb 13, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ron
    Replies:
    1
    Views:
    2,708
    Showjumper
    Jun 24, 2003
  2. Ian
    Replies:
    0
    Views:
    1,390
  3. Hugo
    Replies:
    10
    Views:
    1,320
    Matt Humphrey
    Oct 18, 2004
  4. Nick L
    Replies:
    10
    Views:
    595
    Jerry Coffin
    Aug 31, 2004
  5. jblazi
    Replies:
    5
    Views:
    435
    jblazi
    Aug 16, 2004
Loading...

Share This Page