Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
a = 1 & 2 == 2 # a = (1 & 2) == 2 # => false a = 1 and 2 == 2 # => true 2 == 2 and not 1 == 2 # => true 2 == 2 && not 1 == 2 # => syntax error, unexpected tINTEGER, expecting '(' 2 == 2 && not (1 == 2) # => true |
&
is bit operation in the above example, but it can also handle bool value operation.
1 2 3 4 5 |
false & true # => false true & true # => true |
Right Side Evaluation
演算子の右側を評価するか否かが違います。 これは優先順位によるものでもあるのですが。
1 2 3 4 5 6 7 8 9 10 11 |
(1 == (s = 1)) & (1 == 2) & ((w = 2) == 3) # => false # w == 2 (1 == (s = 1)) && (1 == 2) && ((w = 2) == 3) # => false # w == nil (1 == (s = 1)) and (1 == 2) and ((w = 2) == 3) # => false # w == nil |
and
, &&
doesn’t evaluate right side when the left side is false
. It is like AndAlso
in Visual Basic.