This is what the docs have to say :
This means that the proc object is the target for the when
clause in the case statement.
This is perhaps a contrived example:
even = proc { |x| x % 2 == 0 } n = 3 case n when even puts "even!" else puts "odd!" end
This works because case/when
is basically done as follows:
if even === n puts "even!" else puts "odd!" end
case/when
checks which branch is being executed by calling ===
in the arguments in the when
clauses, choosing the first one that returns a true value.
Despite its similarity to the equality operator ( ==
), it is not a stronger or weaker form. I am trying to think of ===
as an "belongs" operator. Class
defines it so that you can check whether an object belongs to a class (i.e. it is an instance of a class or a subclass of the class), Range
defines it to check if the argument belongs to a range (i.e. it is included in a range), etc. d. This doesn't really make the Proc
case any clearer, but think of it as a tool for creating your own, owned by operators, as my example above; I defined an object that can determine if something belongs to a set of even numbers.
source share