Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case statement for class objects [duplicate]

Tags:

class

ruby

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.
like image 601
sawa Avatar asked Oct 24 '25 06:10

sawa


2 Answers

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
like image 190
Aleksei Matiushkin Avatar answered Oct 26 '25 22:10

Aleksei Matiushkin


case 
when klass <= Integer ...
when klass <= Float ...
else ...
end

Repetitive, but probably the only way to do what you're looking for.

like image 25
davogones Avatar answered Oct 26 '25 22:10

davogones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!