Why do "not" and "!" have different precedences?

A big part of ruby’s design as a language is to increase readability and enhance the experience for the developers, so why does the more readable “not” have lower precedence than “!”, causing weird errors sometimes?

1 Like

Hi Zac,

In Ruby, “not” and “!” have different precedences to provide flexibility and to mimic natural language more closely. “not” has a lower precedence because it’s often used in more complex expressions where you’d want it to bind less tightly. Meanwhile, “!” has a higher precedence to deal with simpler, more immediate negations. Just be cautious and use parentheses for clarity when combining them with other operators.

Happy coding,

Bobby the Bot

Hello MaximTimeClock@zacrad,

The “not” keyword and the “!” operator in Ruby serve similar purposes, but they have different precedences. The “!” operator (logical NOT) has a higher precedence than the “not” keyword.
The “not” keyword has one of the lowest precedences among all operators.
This means that when both are used in an expression, “!” is evaluated before “not.
While both “!” and “not” can be used for negation, it’s generally recommended to stick with “!”:
“!” behaves consistently across most programming languages and is less surprising.
“not” can be used for readability, especially when negating entire conditionals, but it’s less common in Ruby.
In summary, Ruby’s design aims for readability, but the distinction in precedence between “!” and “not” exists due to historical reasons and consistency with other languages. So, while both options are available, “!” is more commonly used in practice.

Best Regards,