From: "Hal E. Fulton" Date: 2002-09-20T09:47:34+09:00 Subject: Thoughts on improving usage of Regexp#match Please feel free to point out obvious things that I'm not seeing here. I was looking at a piece of code like this: sub1 = "" if str =~ regex sub1 = $1 end and I thought three things: 1. I've never liked the $1 -- I usually avoid Perlish variables, even the common ones. 2. I don't like the if. 3. I don't like having to assign sub1 twice. So I tried writing: sub1 = regex.match(str)[1] || "" In theory this should be the same as the other four lines of code. But it doesn't work because if the match fails, #match returns nil and I can't call [] on nil. So I thought: Why don't I make a special MatchData object that will just return nil for any [] call? Did you know that MatchData doesn't have a 'new' method?? I had to do a silly hack to create a MatchData object before adding a singleton method to it. Here's my code: class Regexp alias :oldmatch :match def match(str) result = self.oldmatch(str) if not result null = /x/.match("x") # No new def null.[](index); nil; end result = null end result end end Thoughts? Hal