Pointless One

Ruby, && & and, || & or

I keep encountering it in many places. So here’s a short guide about Ruby logical operators.

The essential difference between perl-ish (&& and ||) and human-ish (and and or) versions of this operators is priority.

Quick example:

1 2
true or false and false # => false
true || false && false #=> true

This happens because && has higher priority than ||, but and is the same priority as or.

Here’s excerpt from Ruby Operator Precenedce Table listing operators from highest precedence to lowest:

  • &&
  • ||
  • or, and

Also note that and and or have even lower priority than assignment operators.

Know your language.

May 29th, 2010 15:35