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?✗ Incorrect
.class returns the exact class of the object.Which method checks if an object is an instance of a class or its parent classes?
✗ Incorrect
.is_a? checks for the class or any superclass.What will
5.is_a?(Numeric) return?✗ Incorrect
5 is an Integer, which inherits from Numeric, so
.is_a?(Numeric) returns true.If
obj.class == String is true, what does obj.is_a?(Object) return?✗ Incorrect
All classes in Ruby inherit from Object, so
.is_a?(Object) returns true.Which method would you use to check if an object is exactly a certain class, not a subclass?
✗ Incorrect
.instance_of? checks if the object is exactly that class, not subclasses.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.