Bird
0
0

Given this code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Advanced Metaprogramming
Given this code, what will be the output?
class Car
  def initialize(model)
    @model = model
  end
end

car1 = Car.new('Toyota')
car2 = Car.new('Honda')

Car.class_eval do
  def info
    "Model: #{@model}"
  end
end

car1.instance_eval do
  def info
    "Special Model: #{@model.upcase}"
  end
end

puts car1.info
puts car2.info
ASpecial Model: TOYOTA Special Model: HONDA
BModel: Toyota Model: Honda
CModel: Toyota Special Model: HONDA
DSpecial Model: TOYOTA Model: Honda
Step-by-Step Solution
Solution:
  1. Step 1: Understand class_eval adds method to all instances

    info method added by class_eval returns "Model: #{@model}" for all cars.
  2. Step 2: Understand instance_eval overrides method for one object

    car1.instance_eval redefines info only for car1, returning uppercase model with "Special Model:" prefix.
  3. Step 3: Check outputs

    car1.info prints "Special Model: TOYOTA"; car2.info prints "Model: Honda".
  4. Final Answer:

    Special Model: TOYOTA Model: Honda -> Option D
  5. Quick Check:

    class_eval affects all; instance_eval overrides one [OK]
Quick Trick: instance_eval overrides method only on one object [OK]
Common Mistakes:
  • Assuming instance_eval changes all instances
  • Expecting both outputs to be 'Special Model'
  • Confusing which method is called on which object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes