← Back to Ruby Operators

Case Equality Operator

The === is an operator used for a special and powerful form of comparison in Ruby. It is known as the Case Equality Operator. It is most useful for writing expressive case statements with a variety of objects and patterns. This operator might also be referred to as the triple equals operator or the membership operator.

We can use the === directly to check if the value on the right is a member of the value on the left. A range is like a list of values, so we can check if a value falls within the defined range.

> ("1.0.0".."1.2.3") === "1.1.1"
=> true
> ("1.0.0".."1.2.3") === "1.4.1"
=> false

We could just as easily use the #include? method though, which, in my opinion, reads better. So what's the use of knowing we can make this comparison with ===?

Well, the case equality comparison is what Ruby uses under the hood when making checks for a case statement. That leads to some powerful and expressive code.

def check_version(version)
  case version
  when ("0.0.1".."0.8.2")
    puts "You're pre-V1"
  when ("1.0.0".."1.2.3")
    puts "You're on V1"
  when ("2.0.0".."2.3.4")
    puts "You're on V2"
  else
    puts "Not a known version - #{version}"
  end
end

check_version("0.1.2") # => You're pre-V1
check_version("1.2.3") # => You're on V1
check_version("2.0.2") # => You're on V2
check_version("4.2.0") # => Not a known version - 4.2.0

This is just the tip of what we can do with the === operator. Check out the Understanding Ruby - Triple Equals article for a deeper dive.

References