ruby - 在 case 语句中使用类对象

标签 ruby class switch-statement

在 case 语句中使用类对象的最佳方式是什么?假设我有 a,它是 Class 类的一个实例。我想将它与不同的类(class)相匹配。如果我这样做

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

这不会给出预期的结果,因为即使 a == String 例如,a === String 也是不正确的。执行此操作的巧妙方法是什么?

最佳答案

我不会使用 to_s,因为 "String".to_s 会是 "String",所以也许我会使用

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

关于ruby - 在 case 语句中使用类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537895/

相关文章:

ruby - 按降序对字符串数组进行排序

java - 研究对象和类

PHP 逻辑,与特定日期进行比较

c++ - 简单程序 - 菜单只显示一次

c++ - 切换案例的替代方案?

c++ - 使用rspec测试C/C++程序

ruby - 如何在 osx 上使用调试符号从源代码编译 ruby​​?

javascript - 使用 Javascript 更改提交按钮的文本

java - 来自另一个类的 RadioButton setText

python - 如何让我的线程在 Python 中运行?