In the following, lines 29 and 35 are exactly the same. Why are their return value different?
27: str = "ABC123"
#=> "ABC123"
29: "It's a match" if ( str.to_s =~ /w+/ )
#=> nil
30: "It's a match" if ( str.to_s =~ /[a-z]/ )
#=> nil
31: "It's a match" if ( str.to_s =~ /[a-zA-Z]/ )
#=> It's a match
32: "It's a match" if ( str.to_s =~ /[a-z]/ )
#=> nil
33: "It's a match" if ( str.to_s =~ /[\w+\W+]/ )
#=> It's a match
34: "It's a match" if ( str.to_s =~ /[\w+]/ )
#=> It's a match
35: "It's a match" if ( str.to_s =~ /\w+/ )
#=> It's a match
36: "It's a match" if ( str =~ /\w+/ )
#=> It's a match
My initial answer is that one of my expressions that evaluated to true assigned the true to str. That just wouldn’t make sense, though. My working environment is Ruby 1.9.1 with Rails 3.0.10.
In line 29 you forgot to put
\beforew+.Gentle remarks: you don’t need brackets in this case and you don’t need
.to_sas str is already a string.Also in irb it is just easier to use either
str =~ /\w+/or evenstr[/\w+/]to see the result.