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.
Something more functional?
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
case
when klass <= Integer ...
when klass <= Float ...
else ...
end
Repetitive, but probably the only way to do what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With