I was writing some code in an erb template that looked like this:
<% if @user && not @user.errors.empty? -%> #do stuff <% end -%>
This resulted in a syntax error. Huh? What’s wrong with this?
Turns out it’s an outstanding Core Ruby bug.
As shown in the ticket if we have a method foo
def foo(parameter) puts parameter.to_s end
using the ! and the not operator on various method calls show us that the ! and not operator are not interchangeable in practice.
foo(!(1 < 2)) # works fine foo(not(1 < 2)) # generates syntax error foo(not 1 < 2) # generates syntax error foo((not 1 < 2)) # works fine
Changing the my code to the following fixed my issue:
<% if @user && !@user.errors.empty? -%> #do stuff <% end -%>
One thought on “Ruby: ! versus not operator”
This is not a Ruby bug, it’s a Ruby feature. ‘not’ is a control operator, ! is a logical operator. The difference is that ‘not’ has lower priority when evaluating the command. Use ! when you do logical expressions. I agree this is confusing.