Case expressions in ruby and some other functional languages are quite different from their imperative switch statement cousins.
As others have mentioned, case expressions use the ===
method, which is a pattern-defining method. In the a === b
paradigm, a
is a pattern which describes a collection of possible instances. b
is an instance which potentially fits into that pattern / collection. Think of a === b
as:
does 'a' describe 'b'?
or
does 'a' contain 'b'?
Once you understand this, String === String #=> false
is not so surprising because String
is an instance of Class
so it fits into the Class
pattern.
The other unique distinction between case expressions and switch statements is that case expressions are just that: expressions. Which means you can do cool stuff like this:
puts case v.name
when "String"
:String
else
:other
end if v.is_a? Class
This code executes only if v
is a class, then switches on v.name
and puts
whatever you want, based on the name of the class.
Because of ruby's nature as a duck-typed language, it's exceedingly rare to have a class in a variable and need to switch on it. If you're frustrated that case
isn't as elegant as you had hoped, give us more context about your goal and we might be able to come up with an elegant solution which avoids switch all together.