红宝石中的!=〜比较运算符是什么? [英] What is the !=~ comparison operator in ruby?

查看:110
本文介绍了红宝石中的!=〜比较运算符是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了这个操作员:

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]
<=> == === != =~ !~

此外,Regexp类具有一元~运算符:

Also, the Regexp class has a unary ~ operator:

〜rxp→整数或nil
匹配-将rxp$_的内容匹配.等同于rxp =~ $_.

~ rxp → integer or nil
Match—Matches rxp against the contents of $_. Equivalent to rxp =~ $_.

所以您的表情等同于:

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

Regexp#=~ 运算符(不是与更熟悉的 String#=~ )返回一个数字:

And the Regexp#=~ operator (not the same as the more familiar String#=~) returns a number:

rxp =〜str→整数或nil
匹配-将rxp与str匹配.

rxp =~ str → integer or nil
Match—Matches rxp against str.

因为将字符串与数字进行比较是错误的,所以最终结果为true.

So you get true as your final result because comparing a string to a number is false.

例如:

>> $_ = 'Where is pancakes house?'
=> "Where is pancakes house?"
>> 9 !=~ /pancakes/
=> false
>> ~ /pancakes/
=> 9

这篇关于红宝石中的!=〜比较运算符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆