ruby – 类对象的Case语句
发布时间:2020-12-17 01:50:30 所属栏目:百科 来源:网络整理
导读:参见英文答案 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |