I would like to expand on the ===
operator.
===
is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with ===
as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does ===
do?
===
is the pattern matching operator!
===
matches regular expressions===
checks range membership===
checks being instance of a class ===
calls lambda expressions===
sometimes checks equality, but mostly it does notSo how does this madness make sense?
Enumerable#grep
uses ===
internallycase when
statements use ===
internallyrescue
uses ===
internallyThat is why you can use regular expressions and classes and ranges and even lambda expressions in a case when
statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value
too, as well as with grep
method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]