From: dblack@... Date: 2002-09-20T10:11:30+09:00 Subject: Re: Thoughts on improving usage of Regexp#match Hi -- On Fri, 20 Sep 2002, Hal E. Fulton wrote: > 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. You could do: sub1 = regex.match(str).to_a[1].to_s > So I thought: Why don't I make a special > MatchData object that will just return nil > for any [] call? [...] > Thoughts? Would you have to test the [0] element to see whether the match had succeeded? David -- David Alan Black | Register for RubyConf 2002! home: dblack@candle.superlink.net | November 1-3 work: blackdav@shu.edu | Seattle, WA, USA Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com