Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Advanced Metaprogramming
What will be the output of this Ruby code?
class Dog
  def initialize(name)
    @name = name
  end
end

fido = Dog.new('Fido')
fido.instance_eval { def speak; "Woof! I'm #{@name}"; end }
puts fido.speak

rex = Dog.new('Rex')
puts rex.respond_to?(:speak)
AWoof! I'm Fido false
BWoof! I'm Fido true
CNoMethodError for fido.speak
DWoof! I'm Fido NoMethodError for rex.speak
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance_eval adds method to one object

    The speak method is added only to fido, not to other Dog instances.
  2. Step 2: Check outputs

    fido.speak prints "Woof! I'm Fido". rex.respond_to?(:speak) returns false because rex has no speak method.
  3. Final Answer:

    Woof! I'm Fido false -> Option A
  4. Quick Check:

    instance_eval adds method to one object only [OK]
Quick Trick: instance_eval adds method to one object only [OK]
Common Mistakes:
  • Assuming all instances get the new method
  • Expecting true for rex.respond_to?(:speak)
  • Confusing instance_eval with class_eval

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes