在 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/