At Hashrocket we are always expressing our views on code, both the good and the bad, about both our own code and code written by others. Recently, the issue of when to use the two flavors of Ruby logic operators: the punctation operators &&, ||, ! or the english operators and, or, not.

Developers new to Ruby1 should be following the rule to only use the punctuation operators for logic:

editable = user.admin? || item.editable?
if user.admin? && item.editable?

and the english operators for flow control:

render :action => 'edit' and return if editable

Once developers are proficient (see below for a quiz!) in Ruby, this rule should become a rule of thumb or just ignored. For example, this reads better with and:

if user.admin? and item.editable?

So how do you know if you should be following the rule or just be aware of it? Answer this:

What happens if we replace the || with or in the first example and why?2

1 Excluding those who are proficient in other languages and already recognize the issue.

2 Did not know the answer? Take a minute and learn Ruby’s operator precedence

blog comments powered by Disqus