Bird
0
0

What will this Ruby code print?

medium📝 Predict Output Q5 of 15
Ruby - Metaprogramming Fundamentals

What will this Ruby code print?

class CatchAll
  def method_missing(name, *args)
    if name.to_s.start_with?('say_')
      "You said: #{args.join(' ')}"
    else
      super
    end
  end
end
obj = CatchAll.new
puts obj.say_hello('Ruby')
ANoMethodError: undefined method `say_hello'
BYou said: Ruby
CYou said: say_hello Ruby
Dsuper
Step-by-Step Solution
Solution:
  1. Step 1: Check method_missing condition

    If method name starts with 'say_', it returns a string with joined arguments.
  2. Step 2: Call obj.say_hello('Ruby')

    Method name is 'say_hello', so condition matches and returns 'You said: Ruby'.
  3. Final Answer:

    You said: Ruby -> Option B
  4. Quick Check:

    Conditional method_missing returns custom string = A [OK]
Quick Trick: Use conditions inside method_missing to handle specific method patterns [OK]
Common Mistakes:
  • Expecting super to be called always
  • Ignoring method name string conversion
  • Confusing output with method name included

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes