The Difference between is_a?, kind_of? and instance_of? in Ruby

09/24/2021

Contents

In this article, you will learn about the difference between is_a?, kind_of? and instance_of? in Ruby.

The difference between is_a?, kind_of? and instance_of?

In Ruby, there are three methods that are used to determine the class of an object: is_a?, kind_of?, and instance_of?. While all three methods can be used to check an object’s class, they behave slightly differently and have different use cases.

is_a? and kind_of? are synonyms, so they behave identically. They return true if the object belongs to the specified class or any of its subclasses. For example:

class Animal
end

class Mammal < Animal
end

class Cat < Mammal
end

my_cat = Cat.new

my_cat.is_a?(Cat)     # true
my_cat.is_a?(Mammal)  # true
my_cat.is_a?(Animal)  # true
my_cat.is_a?(Object)  # true

instance_of?, on the other hand, only returns true if the object is an instance of the specified class, not any of its subclasses. For example:

my_cat.instance_of?(Cat)    # true
my_cat.instance_of?(Mammal) # false
my_cat.instance_of?(Animal) # false
my_cat.instance_of?(Object) # false

It's important to note that instance_of? only returns true if the object is an exact instance of the specified class, and not a subclass or superclass. This makes it less commonly used than is_a? and kind_of?.

In general, you should use is_a? or kind_of? to check whether an object is of a certain class or any of its subclasses. If you want to ensure that an object is an exact instance of a specific class, use instance_of?.