Bird
0
0

Given this code, what will obj.foo.bar output?

hard📝 Application Q9 of 15
Ruby - Metaprogramming Fundamentals

Given this code, what will obj.foo.bar output?

class CatchAll
  def method_missing(name, *args)
    puts "Called #{name} with #{args.inspect}"
    self
  end
end
obj = CatchAll.new
obj.foo.bar
ACalled bar with []
BCalled foo with []
CCalled foo with []\nCalled bar with []
DNoMethodError for bar
Step-by-Step Solution
Solution:
  1. Step 1: Analyze obj.foo call

    Since foo is missing, method_missing prints "Called foo with []" and returns self.
  2. Step 2: Analyze .bar call on returned self

    bar is also missing, so method_missing prints "Called bar with []" and returns self again.
  3. Final Answer:

    Called foo with []\nCalled bar with [] -> Option C
  4. Quick Check:

    method_missing chaining returns self, prints each call [OK]
Quick Trick: Return self in method_missing to allow chaining [OK]
Common Mistakes:
  • Expecting NoMethodError on second call
  • Only printing first call output
  • Not returning self to enable chaining

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes