0
0
Rubyprogramming~15 mins

Included hook in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Included Hook in Ruby Modules
📖 Scenario: Imagine you are building a simple system where different classes can share a greeting message. You want to use a Ruby module to add this greeting feature to any class that includes it. To make it more interesting, you want to print a message automatically when the module is included in a class.
🎯 Goal: You will create a Ruby module with an included hook that prints a message when included. Then, you will include this module in a class and use the shared greeting method.
📋 What You'll Learn
Create a module called Greeter with a method greet that returns the string "Hello!".
Add an included hook inside the Greeter module that prints "Greeter module included!" when the module is included in a class.
Create a class called Person that includes the Greeter module.
Create an instance of Person and call the greet method, then print the result.
💡 Why This Matters
🌍 Real World
Modules with included hooks are useful to add shared behavior and setup code automatically when modules are included in classes, common in Ruby libraries and frameworks.
💼 Career
Understanding modules and hooks is important for Ruby developers working on code reuse, gems, and Rails applications.
Progress0 / 4 steps
1
Create the Greeter module with a greet method
Create a module called Greeter with a method greet that returns the string "Hello!".
Ruby
Need a hint?

Define a module with module Greeter and add a method greet that returns the greeting string.

2
Add the included hook to the Greeter module
Inside the Greeter module, add an included hook method that takes a parameter base and prints "Greeter module included!".
Ruby
Need a hint?

The included hook is a class method inside the module. Use def self.included(base) to define it.

3
Create the Person class and include the Greeter module
Create a class called Person and include the Greeter module inside it.
Ruby
Need a hint?

Define the class with class Person and include the module using include Greeter.

4
Create a Person instance and print the greeting
Create an instance of Person called person. Then call person.greet and print the result.
Ruby
Need a hint?

Create the object with person = Person.new and print the greeting with puts person.greet.