Bird
0
0

Given this class, what will obj.foo.bar(1) output?

hard📝 Application Q15 of 15
Ruby - Metaprogramming Fundamentals

Given this class, what will obj.foo.bar(1) output?

class CatchAll
  def method_missing(name, *args)
    if name == :bar
      "Handled bar with #{args[0]}"
    else
      self
    end
  end
end

obj = CatchAll.new
puts obj.foo.bar(1)
ANoMethodError for foo
BHandled bar with nil
Cself
DHandled bar with 1
Step-by-Step Solution
Solution:
  1. Step 1: Trace obj.foo call

    Calling obj.foo triggers method_missing with name=:foo, which returns self (the object itself).
  2. Step 2: Trace .bar(1) call on returned self

    Calling .bar(1) triggers method_missing with name=:bar and args [1], which returns "Handled bar with 1".
  3. Final Answer:

    Handled bar with 1 -> Option D
  4. Quick Check:

    Chained method_missing returns handled string [OK]
Quick Trick: method_missing can return self to chain calls [OK]
Common Mistakes:
  • Expecting NoMethodError on first call
  • Not realizing method_missing returns self for chaining
  • Assuming args are missing for bar method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes