Consider this Ruby class that uses method_missing to catch undefined method calls:
class CatchAll
def method_missing(name, *args)
"Called #{name} with #{args.join(", ")}"
end
end
obj = CatchAll.new
puts obj.any_method(1, 2, 3)What will this print?
class CatchAll def method_missing(name, *args) "Called #{name} with #{args.join(", ")}" end end obj = CatchAll.new puts obj.any_method(1, 2, 3)
Think about what method_missing does when a method is not found.
The method_missing method catches calls to undefined methods. It receives the method name and arguments. Here, it returns a string showing the method name and arguments passed. So calling any_method(1, 2, 3) prints Called any_method with 1, 2, 3.
Choose the correct statement about Ruby's method_missing method.
Think about when Ruby decides to call method_missing.
method_missing is triggered only when Ruby cannot find a method with the given name on the object. It does not run before existing methods, does not define methods permanently, and can handle any arguments.
Look at this Ruby code:
class RecursiveCatch
def method_missing(name, *args)
method_missing(name, *args)
end
end
obj = RecursiveCatch.new
obj.any_methodWhy does this cause a SystemStackError?
Think about what happens when method_missing calls itself.
The method_missing method calls itself recursively with the same arguments and no stopping condition. This causes infinite recursion, leading to a SystemStackError (stack overflow).
Choose the correct Ruby code snippet that overrides method_missing to print the missing method name and arguments.
Remember the correct parameters for method_missing.
The correct signature is method_missing(name, *args). Option A uses this and joins the arguments properly. Option A misses the splat operator, so args is not an array. Option A has wrong parameter order. Option A ignores arguments.
Examine this Ruby class:
class DynamicResponder
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.start_with?("say_") || super
end
def method_missing(method_name, *args)
if method_name.to_s.start_with?("say_")
"You called #{method_name} with #{args.join(", ")}"
else
super
end
end
end
obj = DynamicResponder.new
puts obj.say_hello("world")
puts obj.unknown_methodWhat will be the output?
class DynamicResponder def respond_to_missing?(method_name, include_private = false) method_name.to_s.start_with?("say_") || super end def method_missing(method_name, *args) if method_name.to_s.start_with?("say_") "You called #{method_name} with #{args.join(", ")}" else super end end end obj = DynamicResponder.new puts obj.say_hello("world") puts obj.unknown_method
Think about how respond_to_missing? and method_missing work together.
The method say_hello starts with "say_", so method_missing handles it and returns the string. The unknown_method does not start with "say_", so method_missing calls super, which raises NoMethodError. The respond_to_missing? method helps respond_to? but does not prevent errors.