How to get the Parent of an Object's Class in Ruby

Published: Thursday, May 19, 2022
Updated: Friday, May 20, 2022

Greetings, friends! We learned in the last article how to get the class name of an object in Ruby. Now, it's time to get the parent class name! We can use the Class#superclass method to get the name of any object's parent class.

ruby
Copied! ⭐️
class Animal
  def speak
    puts "Grrr"
  end
end

class Cat < Animal
  def speak
    puts "Meow!"
  end
end

cat = Cat.new
puts cat.class # Cat
puts cat.class.superclass # Animal
puts cat.class.superclass.superclass # Object
tip
You can try out this code by copying and pasting it to run.rb.

Notice how we can figure out the inheritance chain by calling the superclass method multiple times. Eventually, we find out that our custom class inherits from Object which makes sense, since practically everything in Ruby is an object.

Lets look at integers, strings, booleans, and other types of objects. By calling the Class#superclass method, we can see that each of these types inherit from Object.

ruby
Copied! ⭐️
puts 0.class # Integer
puts 0.class.superclass # Numeric
puts 0.class.superclass.superclass # Object
puts "-------------"

puts 3.14.class # Float
puts 3.14.class.superclass # Numeric
puts 3.14.class.superclass.superclass # Object
puts "-------------"

puts "".class # String
puts "".class.superclass # Object
puts "-------------"

puts false.class # FalseClass
puts false.class.superclass # Object
puts "-------------"

puts true.class # TrueClass
puts true.class.superclass # Object
puts "-------------"

puts nil.class # NilClass
puts nil.class.superclass # Object
puts "-------------"

puts [].class # Array
puts [].class.superclass # Object
puts "-------------"

hash = {foo: 0, bar: 1, baz: 2}
puts hash.class # Hash
puts hash.class.superclass # Object

Getting the parent class name of an object is useful for learning the internals of Ruby or a Ruby library. You can also use the Class#superclass method to help you debug Ruby code. Sometimes, you may need to figure out how a variable's class hierarchy is defined. Calling the Class#superclass method multiple times is perfect for that.

Resources