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

查看:25
本文介绍了在 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",所以也许我会这样做

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天全站免登陆