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