Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
is_a?, kind_of?, and instance_of? in Ruby check the type of an object, but with different depths.
is_a? and kind_of?
They are equivalent - both check if the object is an instance of a certain class or its descendant.
class Animal; end class Dog < Animal; end dog = Dog.new dog.is_a?(Dog) # true dog.is_a?(Animal) # true - because Dog < Animal dog.kind_of?(Animal) # true - the same
instance_of?
Checks the exact class, without inheritance.
dog.instance_of?(Dog) # true dog.instance_of?(Animal) # false — because it is a descendant, not the class itself
In short:
is_a? and kind_of? - check through the inheritance chain
instance_of? - checks only the specific class
This post doesn't have any additions from the author yet.