Recall & Review
beginner
What is the purpose of the
included hook in Ruby modules?The <code>included</code> hook runs automatically when a module is included in a class or another module. It allows you to add extra behavior or setup at the moment of inclusion.Click to reveal answer
beginner
How do you define an
included hook inside a Ruby module?You define a class method named <code>self.included(base)</code> inside the module. The <code>base</code> parameter is the class or module that includes this module.Click to reveal answer
intermediate
What can you do inside the
included hook method?Inside <code>included</code>, you can add methods, extend the including class with class methods, or perform setup tasks like adding callbacks or validations.Click to reveal answer
intermediate
Example: What will happen when this module is included?<br><pre>module Greetings
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def say_hello
"Hello!"
end
end
end
class Person
include Greetings
end
Person.say_hello</pre>The <code>included</code> hook extends the <code>Person</code> class with the <code>ClassMethods</code> module. So calling <code>Person.say_hello</code> will return <code>"Hello!"</code>.Click to reveal answer
intermediate
Why is the
included hook useful compared to just including a module?It lets you run extra code exactly when the module is included, like adding class methods or setting up behavior, which you can't do by just including instance methods.Click to reveal answer
What argument does the
included hook method receive?✗ Incorrect
The
included method receives the including class or module as an argument, allowing you to modify it.Which keyword is used to define the
included hook inside a module?✗ Incorrect
The
included hook is defined as a class method with self.included(base).What is a common use of the
included hook?✗ Incorrect
The
included hook is often used to add class methods by extending the including class.What happens if you include a module with an
included hook in a class?✗ Incorrect
The
included hook runs right when the module is included in the class.Can the
included hook be used to add instance methods to the including class?✗ Incorrect
Instance methods are added by the module itself; the
included hook is mainly for extra setup like adding class methods.Explain what the
included hook does in Ruby modules and give an example of how it can be used.Think about what happens when you include a module and want to add extra behavior.
You got /3 concepts.
Describe the difference between adding instance methods directly in a module and using the
included hook to add class methods.Consider what kinds of methods belong to instances vs the class itself.
You got /3 concepts.