运维开发网

ruby – 类对象的Case语句

运维开发网 https://www.qedev.com 2020-07-27 20:18 出处:网络 作者:运维开发网整理
参见英文答案 > Using a class object in case statement                                    4个 如果我有可能(或可能不是)Class的实例的klass,我如何检查klass对case语句样式的给定类,以查看它是哪个类的子类? 例如,假设klass碰巧是Fixnum.当我检查klass对整数,浮动,…时,我希望它匹配整数.这
参见英文答案 > Using a class object in case statement                                    4个

如果我有可能(或可能不是)Class的实例的klass,我如何检查klass对case语句样式的给定类,以查看它是哪个类的子类?

例如,假设klass碰巧是Fixnum.当我检查klass对整数,浮动,…时,我希望它匹配整数.这段代码:

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.
更实用的东西?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消