If I have klass
that may (or may not) be an instance of Class
, how can I check klass
against given classes in case-statement style to see which class it is a subclass of?
For example, suppose klass
happens to be Fixnum
. When I check klass
against Integer
, Float
, ..., I want it to match Integer
. This code:
case klass
when Integer ...
when Float ...
else ...
end
will not work because it will check whether klass
is an instance of the classes. I want to check whether klass
is a subclass of the classes (or is itself that class).
This is the best I can do so far, but I feel it may be an overkill and is not efficient:
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.