ruby ruby中`not`和`!`的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27429711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:39:00  来源:igfitidea点击:

Difference between `not` and `!` in ruby

rubyboolean-logic

提问by 0112

I recall reading somewhere that notand !are evaluated differently, and I can't find it in the documentation. Are they synonymous?

我记得在某处读过,not并且!评价不同,我在文档中找不到它。它们是同义词吗?

回答by Brennan

They are almost synonymous, but not quite. The difference is that !has a higher precedence than not, much like &&and ||are of higher precedence than andand or.

它们几乎是同义词,但不完全是。不同之处在于!具有比 更高的优先级not,很像&&并且||and和具有更高的优先级or

!has the highest precedence of all operators, and notone of the lowest, you can find the full table at the Ruby docs.

!具有所有运算符的最高优先级,也是最低的优先级not之一,您可以在 Ruby 文档中找到完整的表格

As an example, consider:

例如,请考虑:

!true && false
=> false

not true && false
=> true

In the first example, !has the highestprecedence, so you're effectively saying false && false.
In the second example, nothas a lower precedence than true && false, so this "switched" the falsefrom true && falseto true.

在第一个示例中,!具有最高优先级,因此您实际上是在说false && false.
在第二个示例中,not具有低于 的优先级true && false,因此这“切换”了falsefromtrue && falsetrue

The general guideline seems to be that you should stick to !, unless you have a specific reason to use not. !in Ruby behaves the same as most other languages, and is "less surprising" than not.

一般准则似乎是您应该坚持!,除非您有特定的使用理由not!在 Ruby 中的行为与大多数其他语言相同,并且比not.

回答by roniegh

An easy way to understand the notoperator is by looking at not true && falseas being equivalent to !(true && false)

理解not运算符的一种简单方法是将其not true && false视为等效于!(true && false)