Using a class object in case statement

2020-02-09 03:26发布

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?

4条回答
劳资没心,怎么记你
2楼-- · 2020-02-09 03:52

I wouldn't use to_s, because "String".to_s would be "String", so maybe I'd do

case
when a == String then ...
when a == Fixnum then ...
end

or

a = String

case [a]
when [String] then puts "String"
when [Array] then puts "Array"
end
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-09 03:55

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.

case a.to_s
when "String" then ...
when "Fixnum" then ...
end
查看更多
不美不萌又怎样
4楼-- · 2020-02-09 04:15

Because

Array === Array # return false

and "case when" means "===", so you meet the problem.

查看更多
仙女界的扛把子
5楼-- · 2020-02-09 04:16

The problem with using something like this:

case a.to_s
when "String" then ...
when "Fixnum" then ...
end

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 than to_s since semantically, you're testing the class's name rather than its string representation; the result may be the same but case a.name would be clearer.

If you want to use a case and deal with subclassing then you could use Module#<= like this:

case
when a <= String then ...
when a <= Fixnum then ...
end

Yes, you have to repeat a in each when but that's just how case works.

查看更多
登录 后发表回答