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:
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 _.
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.
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
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?
Master "Metaprogramming Fundamentals" in Ruby
9 interactive learning modes - each teaches the same concept differently