From: Tomasz Wegrzanowski Date: 2006-08-10T03:31:24+09:00 Subject: Re: How to make objects that can set $1 when obj =~ /(.)/ is called ? On 8/8/06, Mauricio Fernandez wrote: > On Tue, Aug 08, 2006 at 02:51:37PM +0900, Tomasz Wegrzanowski wrote: > > class Foo > > def initialize(t) > > @text = t > > end > > def =~(x) > > @text =~ x > > end > > end > > > > And it works for non-capturing regexps, > > but when we want to capture something > > $1 etc. are bound only within the =~ method, > > and when the method returns they are > > restored to their previous values. > > > > Foo.new("Hello") =~ /(e)/ # => 1 > > $1 # => nil > > > > Is it possible to somehow get =~ like that work, > > even if it takes heavy metaprogramming hackery ? > > [ruby-talk:202600] I finally got a working solution, using Binding.of_caller. Not very elegant, but it works: class Foo def =~(pattern) rv = (@text =~ pattern) Binding.of_caller {|binding| set_rx_vars = eval("lambda{|md| $~ = md}", binding) set_rx_vars.call($~) rv } end end -- Tomasz Wegrzanowski [ http://t-a-w.blogspot.com/ ]