This is what the docs have to say:
It is to allow a proc object to be a target of when
clause in the
case statement.
This is a, perhaps contrived, example:
even = proc { |x| x % 2 == 0 }
n = 3
case n
when even
puts "even!"
else
puts "odd!"
end
It works because the case/when
is basically executed like this:
if even === n
puts "even!"
else
puts "odd!"
end
The case/when
checks which branch to execute by calling ===
on the arguments to when
clauses, picking the first that returns a truthy value.
Despite its similarity to the equality operator (==
) it not a stronger or weaker form of it. I try to think of the ===
operator as the "belongs to" operator. Class
defines it so that you can check if an object belongs to the class (i.e. is an instance of the class or a subclass of the class), Range
defines it as to check if the argument belongs to the range (i.e. is included in the range), and so on. This doesn't really make the Proc
case make more sense, but think of it as a tool for making your own belongs to operators, like my example above; I defined an object that can determine if something belongs to the set of even numbers.
String === "foo" => true
– Palecek