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