Complete the code to define a method that checks if an object responds to a method name.
def respond_to_missing?(method_name, include_private = false) method_name == :[1] end
The respond_to_missing? method should return true if the method name matches the expected symbol, here :foo.
Complete the code to properly override respond_to_missing? to handle a dynamic method.
def respond_to_missing?(method_name, include_private = false) method_name.to_s.start_with?('find_') || [1] end
true or false directly without calling super.nil which is not a boolean.Calling super ensures that the default behavior is preserved for methods not handled explicitly.
Fix the error in the method_missing implementation to correctly handle missing methods.
def method_missing(method_name, *args, &block) if method_name.to_s.start_with?('find_') "Finding record for #{method_name}" else [1] end end
Calling super in method_missing passes the call up the inheritance chain, raising the proper error if the method is truly missing.
Fill both blanks to complete a class that uses respond_to_missing? and method_missing to handle dynamic methods starting with 'get_'.
class DynamicGetter def respond_to_missing?(method_name, include_private = false) method_name.to_s.start_with?([1]) || super end def method_missing(method_name, *args, &block) if method_name.to_s.start_with?([2]) "Got #{method_name}" else super end end end
super in either method.Both respond_to_missing? and method_missing check for method names starting with 'get_' to handle dynamic getters.
Fill all three blanks to complete a class that dynamically responds to methods starting with 'calculate_', returning the calculation name.
class Calculator def respond_to_missing?(method_name, include_private = false) method_name.to_s.start_with?([1]) || super end def method_missing(method_name, *args, &block) if method_name.to_s.start_with?([2]) "Calculating #{method_name.to_s[[3]..]}" else super end end end
super in fallback cases.The class handles dynamic methods starting with 'calculate_'. The slice index 10 removes the prefix to show the calculation name.