Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Ruby - Advanced Metaprogramming
Consider this code:
class Tracker
  def initialize
    @events = []
    [:start, :stop].each do |event|
      define_method(event) { @events << event }
    end
  end
  def events
    @events
  end
end

tracker = Tracker.new
tracker.start
tracker.stop
tracker.start
puts tracker.events.inspect
What is the output?
A[]
B[:start, :start, :stop]
C[:stop, :start, :stop]
D[:start, :stop, :start]
Step-by-Step Solution
Solution:
  1. Step 1: Understand define_method inside loop

    Methods :start and :stop append their symbol to @events when called.
  2. Step 2: Trace method calls

    tracker.start adds :start, tracker.stop adds :stop, tracker.start adds :start again.
  3. Step 3: Check final @events array

    The array is [:start, :stop, :start].
  4. Final Answer:

    [:start, :stop, :start] -> Option D
  5. Quick Check:

    Methods append their symbol in call order [OK]
Quick Trick: define_method inside loop captures current event symbol [OK]
Common Mistakes:
  • Mixing order of events
  • Expecting empty array
  • Confusing symbols with strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes