0
0
Rubyprogramming~5 mins

Type checking with .class and .is_a? in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the .class method do in Ruby?
It returns the exact class of an object. For example, <code>5.class</code> returns <code>Integer</code>.
Click to reveal answer
intermediate
What is the difference between .class and .is_a? in Ruby?
<code>.class</code> checks the exact class of an object, while <code>.is_a?</code> checks if the object is an instance of a class or any of its parent classes (inheritance).
Click to reveal answer
intermediate
How does .is_a? help with inheritance?
It returns <code>true</code> if the object is an instance of the given class or any class it inherits from, making it useful to check for types in a family of classes.
Click to reveal answer
beginner
Example: What is the output of "hello".class and "hello".is_a?(String)?
The output of "hello".class is String. The output of "hello".is_a?(String) is true.
Click to reveal answer
intermediate
Can .is_a? return true for a superclass?
Yes, <code>.is_a?</code> returns <code>true</code> if the object is an instance of the class or any of its superclasses.
Click to reveal answer
What does obj.class return in Ruby?
AWhether obj is a string
BTrue if obj is a class
CThe superclass of obj
DThe exact class of obj
Which method checks if an object is an instance of a class or its parent classes?
A.is_a?
B.class
C.to_s
D.superclass
What will 5.is_a?(Numeric) return?
Afalse
Bnil
Ctrue
Derror
If obj.class == String is true, what does obj.is_a?(Object) return?
Afalse
Btrue
Cnil
Derror
Which method would you use to check if an object is exactly a certain class, not a subclass?
A.instance_of?
B.kind_of?
C.is_a?
D.class
Explain the difference between .class and .is_a? in Ruby with examples.
Think about checking exact type vs family of types.
You got /3 concepts.
    How can you use .is_a? to safely check an object's type in a program?
    Consider when you want to accept objects of related types.
    You got /3 concepts.