开发者

How can I know whether a class is inherited from another one? Some methods like is_a?

Simple example:

开发者_开发知识库class A
end

class B < A
end

Then, how can I judge whether class B is inherited from class A? Is there a method somehow like is_a? or maybe called is_child_of??

I can't find one.


You can use the < operator:

B < A will be true, if B is a subclass of A.


In Ruby the class Object has a kind_of? method that does what you want. This is also aliased to is_a?:

module M; end
class A
  include M
end
class B < A; end
class C < B; end
b = B.new
b.kind_of? A   #=> true
b.is_of? B     #=> true
b.kind_of? C   #=> false
b.kind_of? M   #=> true

Also, the class Class has a superclass method:

>> B.superclass
=> A

Note that you can find out what methods any object supports by asking it:

B.methods.sort

The output from this command would have included the kind_of?/is_a?/superclass methods.


You can find all the method definitions for Ruby Objects online.

The closest useful method would be is_a? or kind_of? however read the documentation to be sure they are what you're looking for.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜