Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `not` and `!` in ruby

People also ask

What is not in Ruby?

The “not” keyword gets an expression and inverts its boolean value – so given a true condition it will return false. It works like “!” operator in Ruby, the only difference between “and” keyword and “!” operator is “!” has the highest precedence of all operators, and “not” one of the lowest. Syntax: not expression.

What does != Mean in Ruby?

!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.

What is the difference between OR and || in rails?

As with and , the only difference between or and || is their precedence. Just to make life interesting, and and or have the same precedence, while && has a higher precedence than || .

What is the difference between && || operators and and OR in rails?

The difference between && and and and || and or in Ruby is in the order of precedence. Operator && has a higher precedence than and. But this is generally not an issue unless used with operators which are in between these two, like the ternary and assignment operators. Now this might come as a little surprise!


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.


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