Skip to content

Commit a66039d

Browse files
committed
Expand some wording
1 parent 4379d61 commit a66039d

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

README.adoc

+26-2
Original file line numberDiff line numberDiff line change
@@ -1456,7 +1456,7 @@ ok = got_needed_arguments && arguments_valid
14561456
x = extract_arguments || raise(ArgumentError, "Not enough arguments!")
14571457
----
14581458

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
14601460
becomes confusing:
14611461

14621462
[source,ruby]
@@ -1480,7 +1480,31 @@ if x
14801480
end
14811481
----
14821482

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)
1503+
foz = true || true && false # => true (it's effectively true || (true && false)
1504+
bar = false or true and false # => false (it's effectively (false or true) and false)
1505+
baz = false || true && false # => false (it's effectively false || (true && false))
1506+
----
1507+
****
14841508

14851509
=== Multi-line Ternary Operator [[no-multiline-ternary]]
14861510

0 commit comments

Comments
 (0)