Skip to content

Commit 72c22a3

Browse files
committed
Add Triple Equals: The Case Equality Operator as a Ruby til
1 parent f532b60 commit 72c22a3

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1172 TILs and counting..._
13+
_1173 TILs and counting..._
1414

1515
---
1616

@@ -982,6 +982,7 @@ _1172 TILs and counting..._
982982
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
983983
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
984984
- [Summing Collections](ruby/summing-collections.md)
985+
- [Triple Equals: The Case Equality Operator](ruby/triple-equals-the-case-equality-operator.md)
985986
- [Turn Key And Value Arrays Into A Hash](ruby/turn-key-and-values-arrays-into-a-hash.md)
986987
- [Turning Any Class Into An Enumerator](ruby/turning-any-class-into-an-enumerator.md)
987988
- [Turning Things Into Hashes](ruby/turning-things-into-hashes.md)
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Triple Equals: The Case Equality Operator
2+
3+
The standard equality operator in Ruby is the double equals (`==`).
4+
5+
```ruby
6+
> 2 + 2 == 4
7+
=> true
8+
```
9+
10+
Ruby supports another operator that looks sneakily like this, but with
11+
different behavior. It's the triple equals (`===`) which is called the [case
12+
equality
13+
operator](https://ruby-doc.org/core-3.0.3/Object.html#method-i-3D-3D-3D) (or
14+
case subsumption operator).
15+
16+
Though the specific behavior can be overridden on a class by class basis, the
17+
operator is generally used to check if the first operand is a bucket that the
18+
second operand fits into.
19+
20+
Here are some examples:
21+
22+
```ruby
23+
> (1..10) === 5
24+
=> true
25+
> (1..10) === 13
26+
=> false
27+
28+
> Integer === 7
29+
=> true
30+
> Integer === 'nope'
31+
=> false
32+
33+
> /fun/ === "fundamentals"
34+
=> true
35+
> /taco/ === "fundamentals"
36+
=> false
37+
38+
> Object === String
39+
=> true
40+
> String === Object
41+
=> false
42+
```
43+
44+
It's important to understand how this works because `===` is the operator used
45+
under the hood by Ruby's case statements.
46+
47+
[source](https://stackoverflow.com/questions/4467538/what-does-the-operator-do-in-ruby/4467823#4467823)

0 commit comments

Comments
 (0)