On Friday 19 August 2005 5:33 am, Austin Ziegler wrote:

> I've been programming in Ruby for a while now, and I only know the
> meanings of $1..$9, $0 (use it all the time -- there's no other
> option, as far as I know), $! and $? (only because of shell
> programming) and $: (but I usually use $LOAD_PATH). The only one
> you'll typically see in my code is $0. And that only for command-line
> utility runners.

Austin, if you use the object interface for dealing with regular expressions, 
you need not touch $1, $2, $3, etc...

a = 'abc 123 you and me'
my_match = /(\d+)/.match(a)
puts my_match[1]

=> 123

my_match has a MatchData object.  Treat it like an array, and index 0 contains 
the whole match, while 1 through n contain the captures from the various 
parens in the regex.   Or you can call #captures to get an array containing 
just the captures.

This took a bit longer for me to shift to using over the Perlish $1 .. $9 
syntax, because for some quick things, $1 is a lot faster to use than 
capturing matchdata and referencing it.  Over time, though, I've grown to 
prefer it because it just reads better, to me, especially when I start doing 
complex things with matches.


Kirk Haines



Kirk Haines