How to Get Object Type using kind_of, instance_of, and is_a In Ruby
-
Use the
is_a
to Check the Type of Object in Ruby -
Use the
kind_of?
to Check the Type of Object in Ruby -
Use the
instance_of?
to Check the Type of Object in Ruby
In Ruby, we may need to check the object type from time to time. Several methods accomplish this, including is_a
, kind_of
, and instance_of
.
Use the is_a
to Check the Type of Object in Ruby
Let’s start by making our class:
class Animal; end
dog = Animal.new
We can use is a?
to determine the type of dog
:
dog.is_a?(String)
# => false
dog.is_a?(Animal)
# => true
Dog
is not a string. It’s an object of the Animal
class.
The is a?
method is interesting because it checks for the current class of an object and its ancestors.
It will return true
if the object’s ancestors contain any class that matches the argument.
class Mammal < Animal; end
whale = Mammal.new
Whales are mammals that are also animals in the natural world. What was it like in Ruby?
Ruby excellently performs the necessary checks:
whale.is_a?(Mammal)
# => true
whale.is_a?(Animal)
# => true
Let’s take a look at the whales’ ancestors:
whale.class.ancestors
Output:
=> [Mammal, Animal, Object, Kernel, BasicObject]
Because Animal
is present in the returned array, whale.is a?(Animal)
is also true
.
Use the kind_of?
to Check the Type of Object in Ruby
The is_a?
is an alias for kind of?
.
dophin = Mammal.new
dophin.is_a?(Animal)
# => true
dophin.is_a?(Mammal)
# => true
Use the instance_of?
to Check the Type of Object in Ruby
Unlike is a?
, the instance of?
does not check the object’s ancestors. If an object is an instance of the given class, it returns true
; otherwise, it returns false
.
cat = Mammal.new
cat.instance_of?(Mammal)
# => true
cat.instance_of?(Animal)
# => false