Metaprogramming Basics
Respond To
respond_to? checks whether an object can receive a method before calling it.
Respond To
respond_to.rb
method_name =
text = "ruby"
can_call = text.respond_to?(method_name)
result = can_call ? text.public_send(method_name) : "unavailable"
puts "method=#{method_name}"
puts "can_call=#{can_call}"
puts "result=#{result}"
method_name =
text = "ruby"
can_call = text.respond_to?(method_name)
result = can_call ? text.public_send(method_name) : "unavailable"
puts "method=#{method_name}"
puts "can_call=#{can_call}"
puts "result=#{result}"
method_name =
text = "ruby"
can_call = text.respond_to?(method_name)
result = can_call ? text.public_send(method_name) : "unavailable"
puts "method=#{method_name}"
puts "can_call=#{can_call}"
puts "result=#{result}"
respond to
Checking `respond_to?` makes a dynamic call easier to explain and safer to trace.