From: Stefan Rusterholz Date: 2008-12-11T17:44:43+09:00 Subject: Re: lambda with $1 fails as gsub block Mike Gold wrote: > > I came across this problem: > > def meth(replace) > ">x".gsub(%r!(\W)x!, &replace) > end > > replace = lambda { |match| > puts "$1 is #{$1.inspect}" > } > > ">x".gsub(%r!(\W)x!, &replace) # => $1 is ">" > > "" =~ %r!! # reset $1 > > meth(replace) # => $1 is nil > > Apparently $1 is bound in a peculiar way: Interesting issue. A work-around: module MDGsub def md_gsub(pattern) gsub(pattern) { yield($~) } end end class String include MDGsub end block = proc { |md| p [md.string, *md.captures] } ">x".md_gsub(%r!(\W)x!, &block) # -> [">x", ">"] I hope that helps for the moment. Regards Stefan -- Posted via http://www.ruby-forum.com/.