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?✗ Incorrect
is_a? returns true if the object is an instance of the class or any subclass.Which method is equivalent to
is_a? in Ruby?✗ Incorrect
kind_of? does the same type check as is_a?.What will
"hello".is_a?(String) return?✗ Incorrect
The string "hello" is an instance of String, so it returns true.
What is the difference between
is_a? and instance_of??✗ Incorrect
instance_of? returns true only if the object is exactly that class, not subclasses.If
num = 10, what does num.is_a?(Integer) return?✗ Incorrect
10 is an Integer, so it returns true.
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.