简体   繁体   English

ruby中的!=〜比较运算符是什么?

[英]What is the !=~ comparison operator in ruby?

I found this operator by chance: 我偶然发现了这个算子:

ruby-1.9.2-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 : 此外,Regexp类有一个一元~运算符

~ rxp → integer or nil ~rxp→整数或零
Match—Matches rxp against the contents of $_ . 匹配匹配$_的内容rxp Equivalent to rxp =~ $_ . 相当于rxp =~ $_

So your expression is equivalent to: 所以你的表达相当于:

"abc" != (/abc/ =~ $_)

And the Regexp#=~ operator (not the same as the more familiar String#=~ ) returns a number: Regexp#=~运算符(与更熟悉的String#=~ )返回一个数字:

rxp =~ str → integer or nil rxp = ~str→整数或nil
Match—Matches rxp against str. 匹配匹配rxp与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

!~=~ NOT !=~的倒数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM