Sunday, August 05, 2007

Ruby: operator precedence of && and = (which also applies to || or)

Recently a bug popped up on my project surrounding code similar to the following sample.

total = shopping_cart.empty? and shopping_cart.total

The problem with the above code is that it evaluates as if it were the snippet below.

(total = shopping_cart.empty?) and shopping_cart.total

It should be obvious that setting the total to true or false is not the intended behavior.

The problem with the original snippet is the usage of the 'and' operator. The Ruby operator precedence table shows that '=' has as higher precedence than the 'and' operator.

The solution is to use the '&&' operator instead of the 'and' operator. The precedence table shows that the '&&' operator has a higher precedence than the '=' operator. Therefore, the following two lines of code are basically the same.

total = shopping_cart.empty? && shopping_cart.total
total = (shopping_cart.empty? && shopping_cart.total)

As the title says, the same rules apply to the precedence of '||' and 'or'.
Post a Comment