0
0
Rubyprogramming~10 mins

Type checking with .class and .is_a? in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Type checking with .class and .is_a?
Start with an object
Check object.class
Compare with a class
Action if exact class
+--No-->
Check object.is_a?(Class)
Action if object is instance or subclass
Action if not matching type
End
We first check the exact class of an object using .class, then check if it is an instance of a class or its subclass using .is_a?.
Execution Sample
Ruby
num = 5
puts num.class
puts num.is_a?(Integer)
puts num.is_a?(String)
This code shows how to check the exact class and type membership of a number.
Execution Table
StepExpressionEvaluationResultExplanation
1num = 5Assign 5 to numnum = 5num now holds the integer 5
2num.classCheck exact class of numIntegernum is exactly an Integer
3num.is_a?(Integer)Check if num is Integer or subclasstruenum is an Integer, so true
4num.is_a?(String)Check if num is String or subclassfalsenum is not a String, so false
💡 All checks done, program ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
numundefined5555
Key Moments - 2 Insights
Why does num.class == Integer return true but num.is_a?(Integer) can also be true for subclasses?
num.class returns the exact class, so it must match exactly. num.is_a?(Integer) returns true if num is an instance of Integer or any subclass, so it is more flexible (see execution_table rows 2 and 3).
Can .is_a? return false even if .class matches?
No, if .class matches exactly, .is_a? will always return true because the object is an instance of that class (see execution_table rows 2 and 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of num.class at step 2?
Atrue
BString
CInteger
Dfalse
💡 Hint
Check the 'Result' column in execution_table row 2
At which step does num.is_a?(Integer) return true?
AStep 3
BStep 2
CStep 4
DNone
💡 Hint
Look at the 'Expression' and 'Result' columns in execution_table row 3
If num was a String, what would num.is_a?(Integer) return?
Atrue
Bfalse
CInteger
DError
💡 Hint
Refer to execution_table row 4 where num is not a String and returns false
Concept Snapshot
Type checking in Ruby:
- Use obj.class to get exact class
- Use obj.is_a?(Class) to check if obj is instance or subclass
- .class == Class checks exact match
- .is_a? returns true for subclasses too
- Useful for flexible type checks
Full Transcript
This visual execution shows how Ruby checks types using .class and .is_a?. First, an object num is assigned the value 5. Checking num.class returns Integer because 5 is exactly an Integer. Using num.is_a?(Integer) returns true because num is an instance of Integer or its subclass. Checking num.is_a?(String) returns false because num is not a String. The difference is .class checks exact class, while .is_a? checks class or subclass membership. This helps decide how to handle objects based on their type.