如果我有klass可能(或可能不是)的实例Class,我如何检查klasscase语句样式中的给定类以查看它是哪个类的子类?
例如,假设klass恰好是Fixnum.当我检查klass时Integer,Float......,我希望它匹配Integer.这段代码:
case klass
when Integer ...
when Float ...
else ...
end
Run Code Online (Sandbox Code Playgroud)
将无法工作,因为它将检查是否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.
Run Code Online (Sandbox Code Playgroud)
更实用的东西?
is_descendant = lambda { |sample, main| main <= sample }
not_a_class = lambda { |x| !x.kind_of?(Class) }
mine = Fixnum
case mine
when not_a_class then raise 'Not a class' # Credits to @brymck
when is_descendant.curry[Float] then puts 'Float'
when is_descendant.curry[Integer] then puts 'Integer'
else raise 'Shit happens!'
end
# ? Integer
Run Code Online (Sandbox Code Playgroud)