What is the best way to use a class object in case statement? Suppose I have a
which is an instance of the Class
class. I want to match it against different classes. If I do
case a
when String then ...
when Fixnum then ...
end
this will not give the intended result because even if a == String
for example, a === String
is not true. What is the clever way to do this?
I wouldn't use
to_s
, because"String".to_s
would be"String"
, so maybe I'd door
My temporary answer is to use
to_s
, but am not sure if this is the best that can be done. Waiting for better answers.Because
and "case when" means "===", so you meet the problem.
The problem with using something like this:
is that it completely misses subclasses so you can get something that is a String but is missed by your first branch. Also,
name
would be a better choice thanto_s
since semantically, you're testing the class's name rather than its string representation; the result may be the same butcase a.name
would be clearer.If you want to use a
case
and deal with subclassing then you could useModule#<=
like this:Yes, you have to repeat
a
in eachwhen
but that's just howcase
works.