How do I get the parent's class name in Ruby

class A
end

class B < A
end

B.superclass # => A
B.superclass.name # => "A"

If you want the full ancestor stack try:

object.class.ancestors

For instance:

> a = Array.new
=> []
> a.class.ancestors
=> [Array, Enumerable, Object, Kernel, BasicObject]

In case google brings anyone here who's working in Rails, what you may want instead is base_class, as superclass will traverse the ActiveRecord inheritance structure as well.

class A < ActiveRecord::Base
end

class B < A
end

> A.superclass
=> ActiveRecord::Base
> B.superclass
=> A

> A.base_class
=> A
> B.base_class
=> A

Even further...

class C < B
end

> C.base_class
=> A

In other words, base_class gives you the top of the inheritance tree but limited to the context of your application. Fair warning though, as far as Rails is concerned "your application" includes any gems you're using, so if you have a model that subclasses something defined in a gem, base_class will return the gem's class, not yours.


Given an object (Instantiated Class) you can derive the parent Class

>> x = B.new
>> x.class.superclass.name
=>"A"