views:

73

answers:

3

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.

A: 

http://ruby-doc.org/core/classes/Object.html#M000372

spektom
Thank u all the same :)
Croplio
+4  A: 

You can use the < operator:

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

cypheon
Thanks, this is what I want :D
Croplio
+1  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.

John Topley
Thanks very much :)
Croplio