Bird
0
0

and method_missing implementation correctly follows the convention?

hard📝 Application Q15 of 15
Ruby - Metaprogramming Fundamentals

You want to create a Ruby class that dynamically handles methods starting with calc_ by returning the method name reversed. Which respond_to_missing? and method_missing implementation correctly follows the convention?

Adef respond_to_missing?(method_name, _) method_name.to_s.start_with?("calc_") end def method_missing(method_name, *args) method_name.reverse end
Bdef respond_to_missing?(method_name, _) true end def method_missing(method_name, *args) method_name.to_s.reverse end
Cdef respond_to_missing?(method_name, _) method_name.to_s.include?("calc_") end def method_missing(method_name, *args) method_name.reverse end
Ddef respond_to_missing?(method_name, _) method_name.to_s.start_with?("calc_") end def method_missing(method_name, *args) if respond_to_missing?(method_name, false) method_name.to_s.reverse else super end end
Step-by-Step Solution
Solution:
  1. Step 1: Verify respond_to_missing? logic

    The correct version returns true only if the method_name.to_s starts with "calc_" and ignores the include_private parameter using _.
  2. Step 2: Verify method_missing logic

    The correct version checks respond_to_missing?(method_name, false) before returning method_name.to_s.reverse, and calls super otherwise.
  3. Final Answer:

    def respond_to_missing?(method_name, _) method_name.to_s.start_with?("calc_") end def method_missing(method_name, *args) if respond_to_missing?(method_name, false) method_name.to_s.reverse else super end end -> Option D
  4. Quick Check:

    Use respond_to_missing? check and call super in method_missing [OK]
Quick Trick: Call super in method_missing unless respond_to_missing? true [OK]
Common Mistakes:
  • Not calling super in method_missing
  • Using include? instead of start_with?
  • Always returning true in respond_to_missing?

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes