Be Careful with Not

One thing that I like with ruby is it have a lot of English sounding keywords: not, and, or, unless, etc. However, you should be aware that these keyword might not be equivalent with their “traditional” counterpart.

Take `not` for example. We use `not` to negate a boolean, which we traditionally use bang (!) for. However, not has different precedence level from `!`. In ruby, `!` has the highest precedence, while not has one of the lowest precedence, like you can see in the ruby docs. This might have surprising effect.

!true && false
=> false
 
not true && false
=> true

In the first example, ! has higher precedence than `&&`, so it will evaluates as `(!true) && false`. However in the second example `not` has lower precedence than `&&`, so it will evaluates as `not(true && false)`.

Another example

a = true
b = not a
SyntaxError
 
b = !a
=> true

Because of this subtle difference, I avoid using not and just use ! every time.

Sources:
https://github.com/bbatsov/ruby-style-guide#bang-not-not
http://stackoverflow.com/questions/27429711/can-someone-explain-not-vs-in-ruby

Leave a Reply

Your email address will not be published. Required fields are marked *