Metaprogramming Basics
Respond To
respond_to? checks whether an object can receive a method before calling it.
respond to
Checking `respond_to?` makes a dynamic call easier to explain and safer to trace.
Respond To
respond_to.rb
Replay: real traced execution (multi-file project)
method_name = "upcase"
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 = "reverse"
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 = "missing"
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 ← upcase, text ← ruby, can_call ← true, result ← RUBY
1method_name→ upcase = "upcase" #@method_name="reverse", "missing"2text→ ruby = "ruby"34can_call→ true = text.respond_to?(method_name)true5result→ RUBY = can_calltrue ? text.public_send(method_name)RUBY : "unavailable"67puts "method=#{method_nameupcase}"8puts "can_call=#{can_calltrue}"9puts "result=#{resultRUBY}"outputmethod=upcase can_call=true result=RUBY
method_name ← reverse, text ← ruby, can_call ← true, result ← ybur
1method_name→ reverse = "reverse"2text→ ruby = "ruby"34can_call→ true = text.respond_to?(method_name)true5result→ ybur = can_calltrue ? text.public_send(method_name)ybur : "unavailable"67puts "method=#{method_namereverse}"8puts "can_call=#{can_calltrue}"9puts "result=#{resultybur}"outputmethod=reverse can_call=true result=ybur
method_name ← missing, text ← ruby, can_call ← false, result ← unavailable
1method_name→ missing = "missing"2text→ ruby = "ruby"34can_call→ false = text.respond_to?(method_name)false5result→ unavailable = can_callfalse ? text.public_send(method_name)(empty) : "unavailable"67puts "method=#{method_namemissing}"8puts "can_call=#{can_callfalse}"9puts "result=#{resultunavailable}"outputmethod=missing can_call=false result=unavailable