Test whether a Ruby class is a subclass of another class

后端 未结 2 1105
情歌与酒
情歌与酒 2021-01-29 21:30

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          


        
相关标签:
2条回答
  • 2021-01-29 21:50

    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.

    0 讨论(0)
  • 2021-01-29 21:51

    Just use the < operator

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

    or use the <= operator

    B <= A # => true
    A <= A # => true
    
    0 讨论(0)
提交回复
热议问题