测试 Ruby 类是否是另一个类的子类

发布于 2024-10-09 02:21:36 字数 503 浏览 0 评论 0原文

我想测试一个类是否继承另一个类,但似乎不存在这样的方法。

class A
end

class B < A
end

B.is_a? A 
=> false

B.superclass == A
=> true

(注意,上面的 is_a? 测试没有任何意义,因为第一个注释正确指出 B.new.is_a?(A) 有意义,但不是通常适用,因为并非每个类都有接受 0 个参数的 #initialize 方法)

我想要的一个简单实现是:

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

但我希望它已经存在。

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

(N.B. the is_a? test above does not make any sense, as the first comment correctly points out B.new.is_a?(A) would make sense, but is not generally applicable, as not every class has a #initialize method that accepts 0 arguments)

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

新人笑 2024-10-16 02:21:36

只需使用 < 运算符

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

或使用 <= 运算符

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

Just use the < operator

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

or use the <= operator

B <= A # => true
A <= A # => true
甜心 2024-10-16 02:21:36

也可用:

B.ancestors.include? A

这与 B B B B B B B B B B B B B B < 的(较短)答案略有不同。 A 因为 B 包含在 B.ancestors 中:

B.ancestors
#=> [B, A, Object, Kernel, BasicObject]

B < B
#=> false

B.ancestors.include? B
#=> true

这是否需要取决于您的用例。

Also available:

B.ancestors.include? A

This differs slightly from the (shorter) answer of B < A because B is included in B.ancestors:

B.ancestors
#=> [B, A, Object, Kernel, BasicObject]

B < B
#=> false

B.ancestors.include? B
#=> true

Whether or not this is desirable depends on your use case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文