respond_to? asks an object whether it can handle a named message. Because every object provides this method, you can check an operation before attempting to call it. section 2.3.2
Guarding a message send
obj = Object.new if obj.respond_to?("talk") obj.talk else puts "Sorry, the object doesn't understand the 'talk' message." end The condition prevents the undefined-method error that would result from calling obj.talk directly. section 2.3.2
respond_to? belongs to Ruby’s introspection and reflection facilities: it examines a running program’s object capabilities. The related methods method lists available method names, while respond_to? answers a focused yes-or-no question. section 2.3 section 2.3.2
The check becomes especially useful with send, when the message name is stored in a variable. It provides a safety net, but it is not automatically a complete security policy: arbitrary user input should be restricted to a predetermined allowlist. section 2.3.3
obj = Object.new
if obj.respond_to?("talk")
obj.talk
else
puts "Sorry, the object doesn't understand the 'talk' message."
end
Inspect the guarded call as a small runnable pattern: test the message name, dispatch only when the object reports support, and handle the alternative explicitly. section 2.3.2
