Bird
0
0

Which of the following is the correct way to define respond_to_missing? in a Ruby class?

easy📝 Syntax Q12 of 15
Ruby - Metaprogramming Fundamentals

Which of the following is the correct way to define respond_to_missing? in a Ruby class?

class MyClass
  def respond_to_missing?(method_name, include_private = false)
    # ???
  end
end
Areturn method_name == :find_user
Breturn true if method_name.to_s.start_with?("find_")
Creturn false
Dreturn method_missing(method_name)
Step-by-Step Solution
Solution:
  1. Step 1: Check the method signature and expected return

    respond_to_missing? should return true or false depending on whether the object can handle the method dynamically.
  2. Step 2: Analyze each option

    return true if method_name.to_s.start_with?("find_") returns true if the method name starts with "find_", which is a common pattern for dynamic methods. return method_name == :find_user only returns true for one exact method, which is valid but less flexible. return false always returns false, which defeats the purpose. return method_missing(method_name) incorrectly calls method_missing, which is not correct here.
  3. Final Answer:

    return true if method_name.to_s.start_with?("find_") -> Option B
  4. Quick Check:

    respond_to_missing? returns true for dynamic method patterns [OK]
Quick Trick: Use method_name.to_s and return true for matching patterns [OK]
Common Mistakes:
  • Calling method_missing inside respond_to_missing?
  • Always returning false
  • Checking method_name without converting to string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes