On Sun, Feb 18, 2007 at 12:00:15AM +0900, Phrogz wrote:
> On Feb 17, 1:39 am, "Robert Dober" <robert.do...@gmail.com> wrote:
> > I was naming regular expressions with it roughly like this
> >
> > Fields=Struct.new(:a,:b,:c)
> > /(x*)(y*)(z*)/ === whatever
> > named= Fields.new( *Regexp.last_match.captures )
>
> Ooh, that's quite cool. Thanks for sharing that!
That's one way of doing it. There was a discussion not too long ago of
doing it with the MatchData itself. Something like (tested, works):
class MatchData
def name_captures(*names)
meta = (class << self; self; end)
names.each_with_index { |name,index|
meta.send(:define_method, name) { captures[index] }
}
self
end
end
named = /(x*)(y*)(z*)/.match(whatever).name_captures(:a, :b, :c)
--Greg