测试Ruby类是否是另一个类的子类 [英] Test whether a Ruby class is a subclass of another class

查看:89
本文介绍了测试Ruby类是否是另一个类的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个类是否继承自另一个类,但似乎没有一个方法。

I would like to test whether a class inherits from another class, but there doesn't seem to exist a method for that.

class A
end

class B < A
end

B.is_a? A 
=> false

B.superclass == A
=> true

我想要的一个简单实现:

A trivial implementation of what I want would be:

class Class
  def is_subclass_of?(clazz)
    return true if superclass == clazz
    return false if self == Object
    superclass.is_subclass_of?(clazz)
  end
end

但是我我希望它已经存在。

but I would expect this to exist already.

推荐答案

只需使用 < operator

Just use the < operator

B < A # => true
A < A # => false

或使用< = 运算符

B <= A # => true
A <= A # => true

这篇关于测试Ruby类是否是另一个类的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆