Recall & Review
beginner
What is the
inherited hook in Ruby?The <code>inherited</code> hook is a special method in Ruby that is called automatically whenever a subclass is created from a class. It lets the parent class react to the creation of its child classes.Click to reveal answer
beginner
How do you define an
inherited hook in a Ruby class?You define a class method named <code>self.inherited(subclass)</code> inside the parent class. Ruby calls this method with the new subclass as the argument whenever a subclass is created.Click to reveal answer
intermediate
What can you do inside the
inherited hook?Inside the
inherited hook, you can run code to customize or track subclasses. For example, you can add methods, set variables, or keep a list of all subclasses.Click to reveal answer
beginner
Example: What will this code print?<br><pre>class Parent
def self.inherited(subclass)
puts "New subclass: #{subclass}"
end
end
class Child < Parent
end</pre>It will print: <br>
New subclass: Child<br>This happens because when Child inherits from Parent, the inherited hook runs and prints the message.Click to reveal answer
intermediate
Why is the
inherited hook useful in Ruby?It helps you automatically run code when new subclasses are made. This is useful for tracking subclasses, adding shared behavior, or setting up configurations without changing each subclass manually.Click to reveal answer
What argument does the
inherited hook receive?✗ Incorrect
The
inherited hook receives the new subclass as its argument.Where do you define the
inherited method?✗ Incorrect
You define
self.inherited(subclass) as a class method inside the parent class.What happens when a subclass is created and the parent class has an
inherited hook?✗ Incorrect
The
inherited method runs automatically when a subclass is created.Which of these is a common use of the
inherited hook?✗ Incorrect
Tracking all subclasses is a common use of the
inherited hook.Can the
inherited hook modify the subclass?✗ Incorrect
The
inherited hook can modify the subclass by adding methods or variables.Explain what the
inherited hook does in Ruby and give a simple example.Think about what happens when you create a new subclass.
You got /3 concepts.
Describe a practical use case for the
inherited hook in a Ruby program.Why would you want to know when a subclass is created?
You got /3 concepts.