Ruby: Difference among and, &&, & , or, ||, |


In Ruby, we can use and, &, &&. And also or, |, || we can use. I researched about their difference.

Environment

  • Ruby 2.4.0

and, &, &&論理積を、 or, ||, |論理和を期待通り計算してくれます。

Difference

The most important difference is operator priority and right side evaluation.

Priority

Here is operator priority.

  • &
  • |, ^
  • >, >=, <, <=
  • ==, !=
  • &&
  • ||
  • .., ...
  • ?:
  • =
  • not
  • and, or

Therefore, calculation is as follows.

& is bit operation in the above example, but it can also handle bool value operation.

Right Side Evaluation

演算子の右側を評価するか否かが違います。 これは優先順位によるものでもあるのですが。

and, && doesn’t evaluate right side when the left side is false. It is like AndAlso in Visual Basic.