From: matt_neuburg@... (Matt Neuburg) Date: 2009-06-11T01:15:07+09:00 Subject: Re: Match data variables Lars Christensen wrote: > I understand that $~ and its friends ($&, $1, ...) are method local, but: > > Can a custom method mimic the behaviour of String#match, String#=~ etc > and set the match data for the caller? > > def expect(pattern) > gets =~ pattern or fail > end > > expect /(\d+)/ > > p $1 #=> nil > p $~ #=> nil :-( > > I would like $~ to contain the match data here. Regexp.last_match is a MatchData object and you can do whatever you like with it. For example: def expect(str, pattern) str =~ pattern Regexp.last_match end res = expect("howdy", /h/) p res.begin(0) You could even set some *other* global to Regexp.last_match, if you're in a "use globals" mood... m.