From: Robert Klemme Date: 2006-08-08T17:25:10+09:00 Subject: Re: How to make objects that can set $1 when obj =~ /(.)/ is called ? Tomasz Wegrzanowski wrote: > Something like that would be a reasonable thing to do: > > 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 ? The simplest solution might be to use #match: class Foo def initialize(t) @text = t end def =~(x) x.match @text end end >> md = Foo.new("Hello") =~ /(e)l/ => # >> md.to_a => ["el", "e"] You can do more of course, like storing MatchData along with your Foo instance etc. What problem are you trying to solve? Kind regards robert