0
0
Rubyprogramming~30 mins

Class_eval and instance_eval in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using class_eval and instance_eval in Ruby
📖 Scenario: Imagine you are working on a Ruby program that manages a simple Car class. You want to dynamically add methods and change behavior at runtime using class_eval and instance_eval.
🎯 Goal: You will create a Car class, then use class_eval to add a method to all cars, and instance_eval to add a method to a single car instance. Finally, you will call these methods to see the results.
📋 What You'll Learn
Create a Car class with an initialize method that sets a @make instance variable
Use class_eval to add a method car_info that returns a string with the car make
Use instance_eval on a car instance to add a method special_feature that returns a custom string
Call and print the results of car_info and special_feature methods
💡 Why This Matters
🌍 Real World
Dynamically changing or adding behavior to classes and objects at runtime is useful in metaprogramming, plugins, or frameworks where flexibility is needed.
💼 Career
Understanding <code>class_eval</code> and <code>instance_eval</code> helps Ruby developers write flexible, dynamic code often required in advanced Ruby applications and libraries.
Progress0 / 4 steps
1
Create the Car class with initialize method
Create a class called Car with an initialize method that takes one parameter make and sets it to an instance variable @make.
Ruby
Need a hint?

Use class Car to start the class. Inside, define def initialize(make) and set @make = make.

2
Add car_info method using class_eval
Use Car.class_eval to add a method called car_info that returns the string "This car is a #{@make}".
Ruby
Need a hint?

Use Car.class_eval do and define def car_info inside the block. Return the string with #{@make}.

3
Add special_feature method to one car instance using instance_eval
Create a new Car instance called my_car with make "Toyota". Then use my_car.instance_eval to add a method called special_feature that returns the string "This car has a sunroof".
Ruby
Need a hint?

Create my_car with Car.new("Toyota"). Then use my_car.instance_eval do to define special_feature method.

4
Call and print car_info and special_feature methods
Print the result of calling car_info on my_car. Then print the result of calling special_feature on my_car.
Ruby
Need a hint?

Use puts my_car.car_info and puts my_car.special_feature to print the messages.