From: Robert Klemme Date: 2011-08-29T18:01:04+09:00 Subject: Re: String#split resets regex captures variables (Ruby 1.8.7) On Mon, Aug 29, 2011 at 10:49 AM, Josh Cheek wrote: > 2011/8/29 Bartosz DziewoƄski > >> I think it makes sense for $1, $2 etc to change any time a regex match >> is performed anywhere in Ruby, it might be even kind of useful in some >> perverse scenarios. That said, you shouldn't use these if you can, >> it's a Perl relic (but I admit, sometimes it's the easiest way). >> > I don't, that means that if you call some method, then it can implicitly and > unintentionally change variables you've set, and the only way to know it is > to go digging through source code. You could empirically experiment with it, > but say the regex was conditionally evaluated, then you'd not know it was > used unless conditions were right, meaning it might not pop up until you > were in production. And actually the situation is much more friendly: $1 etc. are local to stack frame... 10:57:55 ~$ cat -n x.rb 1 def x 2 /(a+)/ =~ "aabb" and $1 3 end 4 5 str = 'abcd' 6 7 if str =~ /(c)(d)/ 8 p [$1, $2] 9 p x 10 p [$1, $2] 11 end 10:58:02 ~$ allruby x.rb CYGWIN_NT-5.1 padrklemme2 1.7.9(0.237/5/3) 2011-03-29 10:10 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] ["c", "d"] "aa" ["c", "d"] ======================================== ruby 1.9.2p290 (2011-07-09 revision 32553) [i386-cygwin] ["c", "d"] "aa" ["c", "d"] ======================================== jruby 1.6.3 (ruby-1.8.7-p330) (2011-07-07 965162f) (Java HotSpot(TM) Client VM 1.6.0_26) [Windows XP-x86-java] ["c", "d"] "aa" ["c", "d"] ======================================== jruby 1.6.3 (ruby-1.9.2-p136) (2011-07-07 965162f) (Java HotSpot(TM) Client VM 1.6.0_26) [Windows XP-x86-java] ["c", "d"] "aa" ["c", "d"] ======================================== 10:58:11 ~$ ... and local to thread: 10:59:54 ~$ cat -n x.rb 1 def x 2 /(a+)/ =~ "aabb" and $1 3 end 4 5 str = 'abcd' 6 7 if str =~ /(c)(d)/ 8 p [$1, $2] 9 Thread.new { /(c+)/ =~ "ccccc" and p $1 }.join 10 p [$1, $2] 11 end 10:59:56 ~$ allruby x.rb CYGWIN_NT-5.1 padrklemme2 1.7.9(0.237/5/3) 2011-03-29 10:10 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] ["c", "d"] "ccccc" ["c", "d"] ======================================== ruby 1.9.2p290 (2011-07-09 revision 32553) [i386-cygwin] ["c", "d"] "ccccc" ["c", "d"] ======================================== jruby 1.6.3 (ruby-1.8.7-p330) (2011-07-07 965162f) (Java HotSpot(TM) Client VM 1.6.0_26) [Windows XP-x86-java] ["c", "d"] "ccccc" ["c", "d"] ======================================== jruby 1.6.3 (ruby-1.9.2-p136) (2011-07-07 965162f) (Java HotSpot(TM) Client VM 1.6.0_26) [Windows XP-x86-java] ["c", "d"] "ccccc" ["c", "d"] ======================================== 11:00:04 ~$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/