在case语句中使用类对象 [英] Using a class object in case statement

查看:152
本文介绍了在case语句中使用类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在case语句中使用类对象的最好方法是什么?假设我有 a ,它是 Class 类的一个实例。我想要匹配它对不同的类。如果我做

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

这不会给出预期的结果,因为即使 a == String 例如, a === String 不是真的。

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?

推荐答案

我不会使用 to_s ,因为String.to_s 会是String p>

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

a = String

case [a]
when [String] then puts "String"
when [Array] then puts "Array"
end

这篇关于在case语句中使用类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆