From: Jacob Fugal Date: 2006-03-30T02:24:41+09:00 Subject: Re: Regexp gotcha On 3/29/06, dblack@wobblini.net wrote: > You should have *some* qualms :-) But in any case, this change is > certainly one I wouldn't make. I have no way of knowing whether > someone has done this somewhere: > > if str =~ re > > and not tested for re being nil because it doesn't affect the outcome > of the test. In fact, my initial guess[1] was that String#=~ is defined something like: class String def =~( other ) other =~ self end end And of course the default Object#=~ is: class Object def =~( other ) false end end (observed by the fact that Object.new =~ Object.new returns false without raising NoMethodException). This is useful, because someone might come along and define #=~ for their new class Foo which is close enough semantically to a Regexp to merit the operator overload, but is not a Regexp. ri tells me that REXML::Light::Node#=~ exists, for example. Doing this would cause that to break. -- Jacob Fugal [1] The actual behavior of String#=~ is documented (from ri): If _obj_ is a +Regexp+, use it as a pattern to match against _str_. If _obj_ is a +String+, look for it in _str_ (similar to +String#index+). Returns the position the match starts, or +nil+ if there is no match. Otherwise, invokes _obj.=~_, passing _str_ as an argument. The default +=~+ in +Object+ returns +false+. However, trying string ~ another_string gives me an exception in irb: $ irb >> "looking for bob..." =~ "bob" TypeError: type mismatch: String given from (irb):1:in `=~' from (irb):1 Is this a documentation bug?