DEV Community

Jared Bears
Jared Bears

Posted on

TIL about the === operator in Ruby

Hey everyone! 👋

The other day I talked about conditionals, and finished off by addressing the case method, which I mentioned uses the === operator.

Today, I want to talk about that "triple equals" operator. It confused me a little bit at first, so I had to really read up on it, and now I'll try my best to explain it in a simple way. It is not used often in programming (in fact, some would suggest you not use it yourself), but it is used "under the hood" by different methods in Ruby, and understanding how it works can help you understand how those methods work.

So, we often use the regular == operator to compare if two things are equal. For instance, 2 == 2 would be true. Well, the === method is kind of like that, but it's a bit more flexible. It's not just for comparing whether two objects are identical – it's used in a special way by different classes to check if something "matches" or "fits" into a certain category.

Let's take an example. Imagine we're working with ranges. Ranges are sets of values between a start and an end. Ranges will use the === operator to check if the value on the right appears within the range. For instance, if we have a range like 1..5, and we want to check if the number 3 is inside that range, we can do 1..5 === 3. If the number is within the range, it will return true. If not, it will be false. So, if a range is on the left, it will check to see if the value on the right is within that range. Or, in other words, if 1..5 === 3 is roughly equivalent to if (1..5).member(3)?

But here's the thing – different classes use the === method differently. For arrays, it checks whether the array contains a certain element. For regular expressions, it's like asking if a string matches the pattern. It's changes its behavior based on the context! You can even use it to check against the class of an object, without directly calling for the class, for instance if Integer === 3 would be equivalent to if 3.class == Integer

It is important to keep in mind though that the behavior is based on the element to the left! 1..5 === 3 is NOT the same as 3 ===1..5`

To sum it up, the === method in Ruby is a special operator used by different classes to do specific kinds of comparisons. It's not just about simple equality like 2 == 2, but rather about checking if something belongs to a particular category or matches a certain pattern.

Top comments (1)

Collapse
 
topofocus profile image
Hartmut B.

'===' is essential to case statements. This is, where the fun starts and most users get familiar with its properties and benefits.