0
0
Rubyprogramming~5 mins

Is_a? and kind_of? for type checking in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the is_a? method do in Ruby?
It checks if an object is an instance of a given class or one of its subclasses. It returns <code>true</code> if yes, otherwise <code>false</code>.
Click to reveal answer
beginner
Is there any difference between is_a? and kind_of? in Ruby?
No, both methods do the same thing. They check if an object belongs to a class or its subclass. They are interchangeable.
Click to reveal answer
beginner
How would you check if the variable <code>obj</code> is a String or a subclass of String?
You can use obj.is_a?(String) or obj.kind_of?(String). Both return true if obj is a String or inherits from String.
Click to reveal answer
beginner
What will 5.is_a?(Numeric) return and why?
It returns <code>true</code> because <code>5</code> is an Integer, and Integer is a subclass of Numeric.
Click to reveal answer
beginner
Why is type checking with is_a? useful in Ruby?
It helps you confirm the kind of object you have before calling methods on it, preventing errors and making your code safer.
Click to reveal answer
What does obj.is_a?(ClassName) check in Ruby?
AIf obj is an instance of ClassName or its subclass
BIf obj is exactly ClassName, no subclasses
CIf obj is a method of ClassName
DIf obj is a variable named ClassName
Which method is equivalent to is_a? in Ruby?
Akind_of?
Binstance_of?
Crespond_to?
Dclass
What will "hello".is_a?(String) return?
Anil
Bfalse
Ctrue
Derror
What is the difference between is_a? and instance_of??
ANeither checks class
B<code>instance_of?</code> checks exact class, <code>is_a?</code> includes subclasses
CThey are exactly the same
D<code>is_a?</code> checks exact class, <code>instance_of?</code> includes subclasses
If num = 10, what does num.is_a?(Integer) return?
Anil
Bfalse
Cerror
Dtrue
Explain how is_a? and kind_of? work for type checking in Ruby.
Think about how Ruby checks if an object belongs to a class or its children.
You got /4 concepts.
    Describe a situation where using is_a? would help prevent errors in Ruby code.
    Imagine you want to call a method only if the object is a string.
    You got /4 concepts.