On Wed, Feb 5, 2014 at 3:56 AM, Dave Castellano <lists / ruby-forum.com> wrote:
> Abinoam Jr. wrote in post #1135563:

> http://www.ruby-doc.org/core-2.1.0/Regexp.html#class-Regexp-label-Special+global+variables
>>
>> Pattern matching sets some global variables :
>> $~ is equivalent to ::last_match;
>> $& contains the complete matched text;
>> $` contains string before match;
>> $' contains string after match;
>> $1, $2 and so on contain text matching first, second, etc capture group;

> Thank you - thats a huge help!

There is one important thing you should know: these global variables
are not really global. They are per thread and per scope.

$ ruby -e '/fo+/ =~ "foo"; p $~;Thread.new {p $~}.join'
#<MatchData "foo">
nil
$ ruby -e 'def m(s) /f.+/ =~ s; p $~ end;/f.+/ =~ "foo"; p $~;m("faa");p $~'
#<MatchData "foo">
#<MatchData "faa">
#<MatchData "foo">
$ ruby -e '/f.+/=~"foo";p $~;1.times {/f.+/=~"faa";p $~};p $~'
#<MatchData "foo">
#<MatchData "faa">
#<MatchData "faa">

This is convenient as it avoids multiple matches to interfere with each other.

Btw. you can also make the regex fill local variables:

$ ruby -e '/(?<match>f.+)/=~"foo";p match'
"foo"
$ ruby -e '/f(?<match>.+)/=~"foo";p match'
"oo"

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/