What is the !=~ comparison operator in ruby?
I found this operator by chance:
ruby-1.9.2开发者_C百科-p290 :028 > "abc" !=~ /abc/
=> true
what's this? It's behavior doesn't look like "not match".
That's not one operator, that's two operators written to look like one operator.
From the operator precedence table (highest to lowest):
[] []=
**
! ~ + -
[unary]
[several more lines]
<=> == === != =~ !~
Also, the Regexp class has a unary ~
operator:
~ rxp → integer or nil
Match—Matchesrxp
against the contents of$_
. Equivalent torxp =~ $_
.
So your expression is equivalent to:
"abc" != (/abc/ =~ $_)
And the Regexp#=~
operator (not the same as the more familiar String#=~
) returns a number:
rxp =~ str → integer or nil
Match—Matches rxp against str.
So you get true as your final result because comparing a string to a number is false.
For example:
>> $_ = 'Where is pancakes house?'
=> "Where is pancakes house?"
>> 9 !=~ /pancakes/
=> false
>> ~ /pancakes/
=> 9
!~
is the inverse of =~
NOT !=~
精彩评论