Define_method for dynamic methods
📖 Scenario: Imagine you are creating a simple program to manage a list of pets. Each pet has a name and a type (like dog, cat, or bird). You want to add special methods dynamically to greet each pet by its type.
🎯 Goal: You will build a Ruby class called Pet that uses define_method to create dynamic greeting methods for each pet type. This way, you can call a method like greet_dog or greet_cat to get a custom greeting.
📋 What You'll Learn
Create a class called
Pet with an initializer that takes name and type.Create a list of pet types:
["dog", "cat", "bird"].Use
define_method inside the Pet class to add greeting methods dynamically for each pet type.Print the greeting message by calling the dynamic method for a pet instance.
💡 Why This Matters
🌍 Real World
Dynamic method creation helps when you want to add many similar methods without writing each one by hand, saving time and reducing errors.
💼 Career
Understanding <code>define_method</code> is useful for Ruby developers working on flexible libraries, DSLs, or metaprogramming tasks.
Progress0 / 4 steps