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
and I thought three things:
- I’ve never liked the $1 – I usually avoid
Perlish variables, even the common ones.
- I don’t like the if.
- I don’t like having to assign sub1 twice.
So I tried writing:
sub1 = regex.match(str) || “”
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:
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