0
0
Rubyprogramming~30 mins

Define_method for dynamic methods in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Pet class with initializer
Create a class called Pet with an initialize method that takes name and type as parameters and saves them as instance variables.
Ruby
Need a hint?

Use def initialize(name, type) and set @name = name and @type = type.

2
Create a list of pet types
Create an array called pet_types with the exact values ["dog", "cat", "bird"].
Ruby
Need a hint?

Use square brackets [] to create the array with the three pet types as strings.

3
Use define_method to add dynamic greeting methods
Inside the Pet class, use pet_types.each do |type| ... end and inside the block use define_method to create a method named greet_#{type} that returns the string "Hello, I am a #{type} named #{@name}!".
Ruby
Need a hint?

Use define_method("greet_#{type}") do ... end inside the loop to create methods dynamically.

4
Create a pet and call the dynamic greeting method
Create a Pet instance called my_pet with name "Buddy" and type "dog". Then print the result of calling my_pet.greet_dog.
Ruby
Need a hint?

Create the pet with Pet.new("Buddy", "dog") and call greet_dog on it.