On Mon, Aug 18, 2003 at 02:43:00PM +0900, Yukihiro Matsumoto wrote:
> |Now, is there any way to propagate $1??
> |We need it if gsub and friends are to be wrapped transparently.
> 
> Explicitly?  You can pass the match data and assign it to $~.

But this doesn't solve the problem, does it?

I don't see how $~ would help in

  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"

Is this just impossible to do in Ruby?

At any rate the behavior of the block is quite strange w.r.t. the binding
of $1. It is very different from that of other variables/globals in the
closure: $1 references the $1 in gsub, instead of the one in old_gsub
or the outer one.

However 

batsman@tux-chan:/tmp$ expand -t2 b.rb

def foo
  "foo" =~ /(foo)/
  yield
end

def bar
  "bar" =~ /(bar)/
  foo { puts "foo: " + $1.inspect }
  yield
end

bar {puts "bar: " + $1.inspect}

puts "1 world".gsub(/(1)/) { $1 + " is one" }

batsman@tux-chan:/tmp$ ruby b.rb
foo: "bar"
bar: nil
1 is one world

So gsub is indeed one special case in that $1 is bound to the "inner $1"
instead of the outer. And there's AFAIK no way to wrap gsub without
breaking it because of that.


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

Turn right here. No! NO! The OTHER right!