And or precendence

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-03-28

. Be careful of precedence when using logical AND and OR in the same statement... it might not be in the order the code has it

I had

 @code_diary = CodeDiary.in_category(@category).find do |code_diary|
   code_diary[:name] == params[:name]
 end || raise_not_found and return
 @name = ...

I noticed that @name was never set.

This was because my code boiled down to

a || b and c

If a was not nil, my expectation was that neither the raise_not_found nor the return would be called.

However the || operator was evaluated first, making things

(a || b) and c

i.e. c was always evaluated.

Takeaways: