Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Advanced Metaprogramming
What will this Ruby code print?
class Sample
  def self.method_added(name)
    puts "Added: #{name}"
  end

  def foo; end
  def bar; end
end
AAdded: foo Added: bar
BAdded: foo
CAdded: bar
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Recognize method_added triggers for each method

    Each time an instance method is defined, method_added is called with that method's name.
  2. Step 2: Count the methods defined

    Two methods, foo and bar, are defined, so two outputs occur.
  3. Final Answer:

    Added: foo Added: bar -> Option A
  4. Quick Check:

    method_added triggers once per method defined [OK]
Quick Trick: method_added runs for every new instance method [OK]
Common Mistakes:
  • Assuming only one call for multiple methods
  • Expecting no output without method calls
  • Confusing instance and class methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes