mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
1.1 KiB
1.1 KiB
Triple Equals: The Case Equality Operator
The standard equality operator in Ruby is the double equals (==).
> 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 (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:
> (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.