Ruby syntax reference says about case statements:
Comparisons are done by operator
===
infact, for example:
ruby -e 'puts (1..3) === 2'
prints true, but:
ruby -e 'puts "foo" === /foo/'
prints false, and also:
ruby -e 'puts :foo === /foo/'
prints false, but all these examples are successful conditions for case statements. How does it works?
The
===operator is not commutative, which means that"foo" === /foo/and/foo/ === "foo"are two very different things. Andcasestatements use the latter order.In fact, your first example, using a range, already shows that that order is being used.
2 === (1..3)wouldn’t work, just as your second and third example don’t.The reason that order is chosen is kind of obvious as well, at least if you’re familiar with how operators in Ruby and OO design in general works.
The
===operator is a normal method, so another way of writing/foo/ === "foo"is/foo/.===("foo")– And that order makes sense because a regular expression does know if it matches a string, but a string has no concept of regular expressions and doesn’t know if it would be matched by one. Extended to your first example, a range does know if an element is part of it, but an element has no idea if it’s part of a range.