0
0
Rubyprogramming~15 mins

Class.new for dynamic class creation in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Class.new for dynamic class creation
📖 Scenario: Imagine you want to create different types of animals dynamically in a program. Instead of writing separate classes for each animal, you can create classes on the fly using Class.new.
🎯 Goal: You will create a dynamic class for an animal, add a method to it, and then create an instance to call that method.
📋 What You'll Learn
Create a dynamic class using Class.new and assign it to a variable called Animal.
Add a method called speak inside the dynamic class that returns the string "Hello from Animal".
Create an instance of the Animal class and assign it to a variable called animal_instance.
Print the result of calling the speak method on animal_instance.
💡 Why This Matters
🌍 Real World
Dynamic class creation is useful when you need to generate classes on the fly based on user input or configuration, such as creating different types of objects without writing separate class files.
💼 Career
Understanding dynamic class creation helps in metaprogramming, which is a powerful technique used in Ruby on Rails and other Ruby frameworks to write flexible and reusable code.
Progress0 / 4 steps
1
Create a dynamic class called Animal
Write a line of code that creates a new class dynamically using Class.new and assigns it to a variable called Animal.
Ruby
Need a hint?

Use Animal = Class.new to create a new class and assign it to Animal.

2
Add a method speak to the Animal class
Add a method called speak inside the Animal class that returns the string "Hello from Animal". Use Animal.class_eval and define the method inside the block.
Ruby
Need a hint?

Use Animal.class_eval do ... end to add methods to the dynamic class.

3
Create an instance of Animal
Create an instance of the Animal class and assign it to a variable called animal_instance.
Ruby
Need a hint?

Use animal_instance = Animal.new to create the instance.

4
Print the result of calling speak on animal_instance
Write a line of code to print the result of calling the speak method on animal_instance.
Ruby
Need a hint?

Use puts animal_instance.speak to print the message.