Middle
What is the '===' operator in Ruby?
sobes.tech AI
Answer from AI
The === operator (triple equals) in Ruby is called the case equality operator.
It is used in case/when expressions and is defined by classes to check whether the right operand belongs to the "category" or "range"" represented by the left operand.
The behavior of the === operator depends on the class of the left operand.
Examples:
- Class
Module: Checks if the right operand is an instance or subclass of the module/class.# Checks if the right operand is an instance of String or its subclass. String === "hello" # => true - Class
Range: Checks if the right operand is within the range.# Checks if 5 is within the range 1..10. (1..10) === 5 # => true - Class
Regexp: Checks if the string matches the regular expression.# Checks if the string "/ruby/" matches the regex /ruby/. /ruby/ === "/ruby/" # => true - Class
Proc: Calls the block with the right operand as an argument.# Calls the block with argument 5. ->(x) { x > 3 } === 5 # => true - Class
Symbol: Compares the symbol with another string or symbol.# Compares the symbol :test with the string "test". :test === "test" # => true
In most other classes, === behaves like ==.
Usage in case/when:
The expression case condition is equivalent to a series of === calls on each when value with condition as the right operand.
# Equivalent to String === value
# Then Integer === value
case value
when String
# ...
when Integer
# ...
end