Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Use respond_to in Ruby: Syntax and Examples

In Ruby, respond_to? is a method used to check if an object can respond to a specific method name. You call it with a symbol or string representing the method, like object.respond_to?(:method_name), which returns true or false depending on whether the method exists.
📐

Syntax

The respond_to? method is called on an object and takes one required argument: the method name as a symbol or string. It returns true if the object has that method, otherwise false.

Optional second argument include_private (boolean) lets you check for private methods if set to true.

ruby
object.respond_to?(:method_name, include_private = false)
💻

Example

This example shows how to check if a string object can respond to the upcase method before calling it.

ruby
str = "hello"
if str.respond_to?(:upcase)
  puts str.upcase
else
  puts "Method not supported"
end
Output
HELLO
⚠️

Common Pitfalls

One common mistake is calling a method without checking respond_to?, which can cause errors if the method doesn't exist on the object.

Another is forgetting that respond_to? checks public methods by default and may return false for private methods unless you pass true as the second argument.

ruby
class Example
  private
  def secret
    "hidden"
  end
end

obj = Example.new

# Wrong: assumes method is public
puts obj.respond_to?(:secret) # false

# Right: check including private methods
puts obj.respond_to?(:secret, true) # true
Output
false true
📊

Quick Reference

UsageDescription
object.respond_to?(:method)Returns true if object has public method
object.respond_to?(:method, true)Returns true if object has method including private
Use before calling a methodAvoids NoMethodError by checking method existence
✅

Key Takeaways

Use respond_to? to check if an object supports a method before calling it.
Pass true as second argument to check for private methods.
Helps prevent errors by verifying method availability.
Works with method names as symbols or strings.
Commonly used in dynamic or flexible code to ensure safety.