What's the Difference Between Using "not" and "!" in a Boolean Context in Ruby?

In Ruby, both, the not keyword and !, are not aliases. In fact, they are two separate operators that perform negation in a boolean context, and differ in terms of operator precedence:

  • ! has the highest precedence of all operators;
  • not has the much lower precedence.

This means that when they're evaluated in an expression, the order of evaluation will be different for one over the other. To demonstrate this, consider, for example, the following:

print (!true && false) #=> false

print (not true && false) #=> true

In the first expression, ! has a higher order of precedence than &&. Therefore, !true is evaluated first, which results in false. Then false && false is evaluated, which results in false. So, the overall result of the expression is false.

In the second expression, not has lower order of precedence than &&. So not true is evaluated after true && false is evaluated. true && false results in false, and then not false results in true. So, the overall result of the expression is true.

Basically, "not true && false" is equivalent to "!(true && false)" and is not the same as "!true && false".


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.