0
0
Rubyprogramming~5 mins

Type checking with .class and .is_a? in Ruby

Choose your learning style9 modes available
Introduction

We use type checking to find out what kind of thing (object) we have. This helps us decide what we can do with it.

When you want to do something only if a value is a number.
When you need to check if an object belongs to a certain group or family of types.
When you want to avoid errors by making sure an object supports certain actions.
When you want to handle different types of objects in different ways.
When debugging to understand what type of data you are working with.
Syntax
Ruby
object.class
object.is_a?(ClassName)

.class tells you the exact type of the object.

.is_a? checks if the object is of a type or inherits from that type.

Examples
This shows the exact type of 5 is Integer.
Ruby
5.class
# => Integer
This shows the exact type of "hello" is String.
Ruby
"hello".class
# => String
This checks if 5 is an Integer or a subclass of Integer. It returns true.
Ruby
5.is_a?(Integer)
# => true
Since String inherits from Object, this returns true.
Ruby
"hello".is_a?(Object)
# => true
Sample Program

This program checks the type of different objects and prints messages based on their type.

Ruby
def check_type(obj)
  puts "Object: #{obj}"
  puts "Type with .class: #{obj.class}"
  if obj.is_a?(String)
    puts "It's a String!"
  elsif obj.is_a?(Integer)
    puts "It's an Integer!"
  else
    puts "It's something else."
  end
end

check_type("Ruby")
check_type(42)
check_type(3.14)
OutputSuccess
Important Notes

.class gives the exact class, but .is_a? can check for parent classes too.

Use .is_a? when you want to allow subclasses, not just exact matches.

Type checking helps avoid errors by confirming what you have before using it.

Summary

.class tells you the exact type of an object.

.is_a? checks if an object is a type or inherits from it.

Use these to write safer and clearer code by knowing what you are working with.