Bird
0
0

Identify the error in this Ruby class using respond_to_missing? and method_missing:

medium📝 Debug Q14 of 15
Ruby - Metaprogramming Fundamentals

Identify the error in this Ruby class using respond_to_missing? and method_missing:

class Broken
  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.start_with?("do_")
  end

  def method_missing(method_name, *args)
    "Doing #{method_name}"
  end
end

b = Broken.new
puts b.do_something
puts b.unknown
Arespond_to_missing? must not have default parameters
Brespond_to_missing? should always return true
Cmethod_missing should call super for unknown methods
Dmethod_missing must not accept *args
Step-by-Step Solution
Solution:
  1. Step 1: Understand method_missing behavior

    method_missing should handle only methods that respond_to_missing? returns true for; otherwise, it should call super to raise NoMethodError.
  2. Step 2: Identify the problem in the code

    Here, method_missing always returns a string, even for unknown methods, so it hides errors and breaks expected behavior.
  3. Final Answer:

    method_missing should call super for unknown methods -> Option C
  4. Quick Check:

    method_missing must call super if method not handled [OK]
Quick Trick: Always call super in method_missing for unhandled methods [OK]
Common Mistakes:
  • Not calling super in method_missing
  • Returning wrong types from method_missing
  • Misusing respond_to_missing? signature

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes