Object#respond_to?
obj.respond_to?(method_name, include_all=false) -> true or false boolean · Updated March 13, 2026 · Core Classes The respond_to? method is a core Ruby reflection method that checks if an object responds to a particular method. It takes a method name (as a Symbol or String) and returns true if the object has a method with that name defined, or false otherwise. This method is fundamental to Ruby’s duck typing philosophy, allowing you to write flexible code that works with any object that “quacks” like a duck.
Syntax
obj.respond_to?(method_name)
obj.respond_to?(method_name, include_all)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
method_name | Symbol or String | — | The name of the method to check for |
include_all | Boolean | false | When true, also checks for private methods |
Examples
Basic usage
str = "hello"
str.respond_to?(:upcase)
# => true
str.respond_to?(:foobar)
# => false
# Works with strings too
str.respond_to?("downcase")
# => true
Checking for private methods
By default, respond_to? returns false for private methods. Pass true as the second argument to include them:
class User
def public_method
"I'm public!"
end
private
def private_method
"I'm secret!"
end
end
user = User.new
user.respond_to?(:private_method)
# => false
user.respond_to?(:private_method, true)
# => true
Dynamic method dispatch
Use respond_to? before calling methods dynamically to avoid NoMethodError:
def process_object(obj)
if obj.respond_to?(:to_json)
puts obj.to_json
elsif obj.respond_to?(:to_s)
puts obj.to_s
else
puts obj.inspect
end
end
Common Patterns
Plugin systems
Many gems use respond_to? to check for optional capabilities:
class PluginManager
def execute_plugins(object)
plugins.each do |plugin|
next unless object.respond_to?(plugin.required_method)
plugin.call(object)
end
end
end
Conditional method calls
Build flexible APIs that work with different object types:
def format_output(item)
formatter = item.respond_to?(:format) ? item : item.to_s
formatter.format
end
Testing for method availability
Check for Ruby version-specific methods:
# Only call if available (Ruby 2.5+)
result = str.respond_to?(:delete_suffix) ? str.delete_suffix("!") : str.chomp
Errors
respond_to? never raises an error. It always returns true or false, even for non-existent method names.