Difference between `not` and `!` in ruby

0112 picture 0112 · Dec 11, 2014 · Viewed 57.8k times · Source

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

Answer

Brennan picture Brennan · Dec 11, 2014

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 and and or.

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

As an example, consider:

!true && false
=> false

not true && false
=> true

In the first example, ! has the highest precedence, so you're effectively saying false && false.
In the second example, not has a lower precedence than true && false, so this "switched" the false from true && false to true.

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.