From: dblack@... Date: 2006-03-29T00:33:24+09:00 Subject: Re: Regexp gotcha Hi -- On Wed, 29 Mar 2006, Pistos Christou wrote: > Hi, all. I was fixing a bug last night, and discovered some > "gotcha"-like behaviour in the process. Consider: > > irb(main):173:0> s = "my string" > => "my string" > irb(main):174:0> r1 = /my/ > => /my/ > irb(main):175:0> r2 = /your/ > => /your/ > irb(main):176:0> r3 = nil > => nil > irb(main):177:0> s =~ r1 > => 0 > irb(main):178:0> s =~ r2 > => nil > irb(main):179:0> s =~ r3 > => false > > s =~ r1 .... That's cool, it gives me the index of the match. > s =~ r2 .... That's cool, it tells me there was no match. > s =~ r3 .... Whoa. > > The reason this "got me" is that I had this code: > > match_result = ( some_string =~ some_regexp ) > if match_result != nil > # Assume there was a match > end > > But the problem is... I had an s =~ r3 case because some_regexp was nil, > and so it was entering my if block when I semantically did not want that > to occur. :( > > So now my code is > > if match_result != nil and match_result != false You could shorten that to: if match_result I'm not sure about the "why" part of the nil/false thing. David -- David A. Black (dblack@wobblini.net) Ruby Power and Light, LLC (http://www.rubypowerandlight.com) "Ruby for Rails" chapters now available from Manning Early Access Program! http://www.manning.com/books/black