Monday, October 20, 2014

Operator precendence

In this post I would like to discuss the difference between Ruby's and / && and or / || operators. Based on prior experience with Java, I would usually use && instead of and (|| instead of or). However, I've seen code samples with and or operators, and so I was under impression that it might've been a more Ruby-ish, human friendly way of writing code. (Plus, I was used to using and (or) when programming in NetLogo).

The truth is that one needs to pay attention to operator precedence in Ruby, as defined in the docs. Thus, the following code snippets will be evaluated differently:

a = true and false      => a = true
b = true && false       => b = false

As described in the docs, = operator takes precedence over and operator, while && takes precedence over = operator.

Putting parenthesis around an expression when using and (or) can help to make sure you are getting the expected behavior. Thus, the following expression will be evaluated to false:

a = (true and false)    => a = false  

Me not knowing this little catch probably explains some of the funny behaviors I was getting in my code sometimes. But I am a big fan of using parenthesis to help me visually break the code into pieces, and this habit probably saved me from bigger troubles.

No comments :

Post a Comment