We use is_a? and kind_of? to check what type an object is. This helps us decide what actions to take based on the object's type.
0
0
Is_a? and kind_of? for type checking in Ruby
Introduction
When you want to check if a variable is a certain type before using it.
When you want to make sure an object belongs to a class or its subclass.
When you want to avoid errors by confirming the object's type before calling methods.
When you want to handle different types of objects differently in your code.
Syntax
Ruby
object.is_a?(ClassName) object.kind_of?(ClassName)
Both is_a? and kind_of? do the same thing in Ruby.
They return true if the object is an instance of the class or its subclass, otherwise false.
Examples
Check if a number is an Integer or a String.
Ruby
5.is_a?(Integer) # returns true "hello".is_a?(String) # returns true 5.is_a?(String) # returns false
Check if an object is a subclass or the exact class.
Ruby
class Animal; end class Dog < Animal; end dog = Dog.new dog.kind_of?(Animal) # returns true dog.kind_of?(Dog) # returns true dog.kind_of?(String) # returns false
Sample Program
This program creates a class Vehicle and a subclass Car. It then checks if my_car is a Car, a Vehicle, or a String.
Ruby
class Vehicle end class Car < Vehicle end my_car = Car.new puts my_car.is_a?(Car) # true puts my_car.is_a?(Vehicle) # true puts my_car.is_a?(String) # false
OutputSuccess
Important Notes
is_a? and kind_of? are interchangeable; use whichever you prefer.
They check inheritance, so subclasses return true for their parent classes.
Use these methods to write safer code that adapts to different object types.
Summary
is_a? and kind_of? check an object's type or its parent types.
They return true if the object is an instance of the class or subclass.
Use them to make decisions based on object types and avoid errors.