You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.adoc
+26-2
Original file line number
Diff line number
Diff line change
@@ -1456,7 +1456,7 @@ ok = got_needed_arguments && arguments_valid
1456
1456
x = extract_arguments || raise(ArgumentError, "Not enough arguments!")
1457
1457
----
1458
1458
1459
-
But avoid several control flow operators in one expression, as that quickly
1459
+
Avoid several control flow operators in one expression, as that quickly
1460
1460
becomes confusing:
1461
1461
1462
1462
[source,ruby]
@@ -1480,7 +1480,31 @@ if x
1480
1480
end
1481
1481
----
1482
1482
1483
-
NOTE: Whether organizing control flow with `and` and `or` is a good idea has been a controversial topic in the community for a long time. But if you do, prefer these operators over `&&`/`||`.
1483
+
NOTE: Whether organizing control flow with `and` and `or` is a good idea has been a controversial topic in the community for a long time. But if you do, prefer these operators over `&&`/`||`. As the different operators are meant to have different semantics that makes it easier to reason whether you're dealing with a logical expression (that will get reduced to a boolean value) or with flow of control.
1484
+
1485
+
.Why is using `and` and `or` as logical operators a bad idea?
1486
+
****
1487
+
Simply put - because they add some cognitive overhead, as they don't behave like similarly named logical operators in other languages.
1488
+
1489
+
First of all, `and` and `or` operators have lower precedence than the `=` operator, whereas the `&&` and `||` operators have higher precedence than the `=` operator, based on order of operations.
1490
+
1491
+
[source,ruby]
1492
+
----
1493
+
foo = true and false # results in foo being equal to true. Equivalent to (foo = true) and false
1494
+
bar = false or true # results in bar being equal to false. Equivalent to (bar = false) or true
1495
+
----
1496
+
1497
+
Also `&&` has higher precedence than `||`, where as `and` and `or` have the same one. Funny enough, even though `and` and `or`
1498
+
were inspired by Perl, they don't have different precedence in Perl.
1499
+
1500
+
[source,ruby]
1501
+
----
1502
+
foo = true or true and false # => false (it's effectively (true or true) and false)
0 commit comments