On Mon, Aug 18, 2003 at 07:38:52AM +0900, Florian Gross wrote:
> Moin!
> 
> This code:
> 
>   class String
>     alias :old_gsub :gsub
>     def gsub(*args, &block)
>       old_gsub(*args, &block)
>     end
>   end
> 
>   "hello world".gsub(/(\w+)/) { print $1; $1 }; print "\n"
> 
> produces this output for me:
> 
>   nilnil
> 
> (I'm using ruby 1.8.0 (2003-08-04) [i386-mswin32] and I'm told that it 
> does the same in the 1.8.0 final, 1.7.3 and 1.6.8 on Linux.)
> 
> Is this behaviour by design or is this a bug? If it's not a bug: Why 
> is $1 changed to nil in this case?

It seems it is by design:

batsman@tux-chan:/tmp$ expand -t2 a.rb
def foo
  puts "Match: #{$1.inspect}"
end

"abcd" =~ /(b)/
foo
puts "Match: #{$1.inspect}"

batsman@tux-chan:/tmp$ ruby a.rb
Match: nil
Match: "b"

So $1 is method-scoped.

Now, is there any way to propagate $1??
We need it if gsub and friends are to be wrapped transparently.

-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

One tree to rule them all,
One tree to find them,
One tree to bring them all,
and to itself bind them.
	-- Gavin Koch <gavin / cygnus.com>