What does respond_to? do and how does it relate to duck typing?
Last updated
respond_to?(:name)returns true if the object can receive that method. Passingtrueas a second argument also checks private/protected methods.It supports duck typing (caring what an object can do, not its class) by branching on behavior instead of
is_a?checks.Methods handled by
method_missingaren't reported unless you also definerespond_to_missing?.
- https://docs.ruby-lang.org/en/3.4/Object.html
- https://medium.com/@mraihanm99/the-power-of-respond-to-rubys-method-checker-a6de7f6617e7
- https://docs.ruby-lang.org/en/3.0/method_documentation_rdoc.html
- https://www.rubydoc.info/stdlib/core/Object:respond_to%3F
- https://dev.to/morinoko/dynamic-method-handling-with-methodmissing-and-respondtomissing-in-ruby-and-rails-oac
- https://docs.ruby-lang.org/en/3.2/Delegator.html
- https://blog.devops.dev/duck-typing-in-ruby-007db78e2742
- https://medium.com/@umairashas/understanding-dynamic-typing-duck-typing-in-ruby-76676da95ea0