From 117856c2aa689e580f649c4211eee87d083d03dd Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 24 Oct 2022 20:05:23 -0500 Subject: [PATCH] Add Precedence Of Logical Operators as a Ruby TIL --- README.md | 3 ++- ruby/precedence-of-logical-operators.md | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 ruby/precedence-of-logical-operators.md diff --git a/README.md b/README.md index d339076..40c5f26 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1259 TILs and counting..._ +_1260 TILs and counting..._ --- @@ -1058,6 +1058,7 @@ _1259 TILs and counting..._ - [Passing Arguments To A Rake Task](ruby/passing-arguments-to-a-rake-task.md) - [Pattern Match Values From A Hash](ruby/pattern-match-values-from-a-hash.md) - [Percent Notation](ruby/percent-notation.md) +- [Precedence Of Logical Operators](ruby/precedence-of-logical-operators.md) - [Question Mark Operator](ruby/question-mark-operator.md) - [Rake Only Lists Tasks With Descriptions](ruby/rake-only-lists-tasks-with-descriptions.md) - [Read The First Line From A File](ruby/read-the-first-line-from-a-file.md) diff --git a/ruby/precedence-of-logical-operators.md b/ruby/precedence-of-logical-operators.md new file mode 100644 index 0000000..97d68e0 --- /dev/null +++ b/ruby/precedence-of-logical-operators.md @@ -0,0 +1,23 @@ +# Precedence Of Logical Operators + +There are two sets of logical operators that you are going to see in Ruby. The +more common and idiomatic set are `!`, `&&`, and `||`. Relative to all the +other operators in the Ruby language, these three have high precedence. + +The other set of logical operators are `not`, `and`, and `or`. These ones have +relatively much lower precedence. Though they work conceptually the same. + +The reason to be aware of the differences in precedence is that if you were to +mix the two sets, you could end up with unexpected results. + +```ruby +> not true && false +=> true +> !true && false +=> false +``` + +To keep my Ruby code idiomatic and to avoid these kinds of potential logical +mixups, I stick to using nearly exclusively the first set—`!`, `&&`, and `||`. + +[source](https://ruby-doc.org/core-2.6.2/doc/syntax/precedence_rdoc.html)