<分区>
如果我有 klass
可能(或可能不是)Class
的实例,我如何检查 klass
对给定的类case-statement 样式来查看它是哪个类的子类?
例如,假设klass
恰好是Fixnum
。当我检查 klass
与 Integer
、Float
时,...,我希望它匹配 Integer
。这段代码:
case klass
when Integer ...
when Float ...
else ...
end
不会工作,因为它会检查 klass
是否是类的实例。我想检查 klass
是否是类的子类(或者它本身就是那个类)。
这是迄今为止我能做的最好的,但我觉得这可能有点矫枉过正而且效率不高:
class ClassMatcher
def initialize klass; @klass = klass end
def === other; other.kind_of?(Class) and other <= @klass end
end
class Class
def matcher; ClassMatcher.new(self) end
end
klass = Fixnum
case klass
when Integer.matcher then puts "It is a subclass of Integer."
when Float.matcher then puts "It is a subclass of Float."
end
# => It is a subclass of Integer.