ruby - 类对象的案例陈述

标签 ruby class

<分区>

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

例如,假设klass 恰好是Fixnum。当我检查 klassIntegerFloat 时,...,我希望它匹配 Integer。这段代码:

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

关于ruby - 类对象的案例陈述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20811342/

相关文章:

actionscript-3 - AS3 中麦克风输入数据的快速傅里叶变换

javascript - 如何循环遍历类并在数组中添加文本

ruby-on-rails - 如何正确检查 ruby​​ 中的嵌套值

ruby - 基本 ruby​​ 脚本未按预期工作

html - 如何在 `class` 和 `id` 之间进行选择

c# - 类方法 : should I always check variables before accessing them?

javascript - 在激活另一个类时添加一个类

ruby - 在 Ruby 中初始化二维数组

ruby - 为什么我不能运行 postgresql 服务器?

ruby-on-rails - Heroku 推送被拒绝,未检测到 Cedar 支持的应用程序(不同问题)