From 72c22a32621275be38e294a992682914f1220c42 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 20 Dec 2021 16:14:12 -0600 Subject: [PATCH] Add Triple Equals: The Case Equality Operator as a Ruby til --- README.md | 3 +- ...riple-equals-the-case-equality-operator.md | 47 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 ruby/triple-equals-the-case-equality-operator.md diff --git a/README.md b/README.md index 43bb8b7..e41477e 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). -_1172 TILs and counting..._ +_1173 TILs and counting..._ --- @@ -982,6 +982,7 @@ _1172 TILs and counting..._ - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md) - [Summing Collections](ruby/summing-collections.md) +- [Triple Equals: The Case Equality Operator](ruby/triple-equals-the-case-equality-operator.md) - [Turn Key And Value Arrays Into A Hash](ruby/turn-key-and-values-arrays-into-a-hash.md) - [Turning Any Class Into An Enumerator](ruby/turning-any-class-into-an-enumerator.md) - [Turning Things Into Hashes](ruby/turning-things-into-hashes.md) diff --git a/ruby/triple-equals-the-case-equality-operator.md b/ruby/triple-equals-the-case-equality-operator.md new file mode 100644 index 0000000..4453c10 --- /dev/null +++ b/ruby/triple-equals-the-case-equality-operator.md @@ -0,0 +1,47 @@ +# Triple Equals: The Case Equality Operator + +The standard equality operator in Ruby is the double equals (`==`). + +```ruby +> 2 + 2 == 4 +=> true +``` + +Ruby supports another operator that looks sneakily like this, but with +different behavior. It's the triple equals (`===`) which is called the [case +equality +operator](https://ruby-doc.org/core-3.0.3/Object.html#method-i-3D-3D-3D) (or +case subsumption operator). + +Though the specific behavior can be overridden on a class by class basis, the +operator is generally used to check if the first operand is a bucket that the +second operand fits into. + +Here are some examples: + +```ruby +> (1..10) === 5 +=> true +> (1..10) === 13 +=> false + +> Integer === 7 +=> true +> Integer === 'nope' +=> false + +> /fun/ === "fundamentals" +=> true +> /taco/ === "fundamentals" +=> false + +> Object === String +=> true +> String === Object +=> false +``` + +It's important to understand how this works because `===` is the operator used +under the hood by Ruby's case statements. + +[source](https://stackoverflow.com/questions/4467538/what-does-the-operator-do-in-ruby/4467823#4467823)