Difference Between "Not" and "!" in Ruby

Difference Between "Not" and "!" in Ruby

Are not and ! synonyms, or are they evaluated differently?

1

3 Answers

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.

5

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

I have an RSpec-driven example here: Ruby's not keyword is not not but ! (not)

In essence:

  • They differ in precedence
  • They are not aliases
  • ! can be overriden, whereas not cannot be overriden
  • when you override ! then not will be overriden too, hence it must be using ! under the hood
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.