liveBook · Manning

Respond_to_missing?

As explained in The Well-Grounded Rubyist, Fourth Edition

respond_to_missing? is a Ruby callback method that lets an object report whether it can respond to a method handled dynamically by method_missing.

respond_to_missing? is the callback that keeps Ruby's introspection consistent with method_missing. When an object handles an otherwise unknown message dynamically, respond_to? can consult this method before answering whether the message is supported. section 15.1.1

Making dynamic setters discoverable

A Person object can turn person.set_age(38) into an age= call through method_missing. Without respond_to_missing?, person.respond_to?(:set_age) reports false even though the call works. Defining respond_to_missing? to recognize set_ makes the query return true; person.method(:set_age) can then produce a method object. section 15.1.1

def respond_to_missing?(m, include_private = false)
  /set_/.match(m) || super
end

The callback recognizes dynamically handled set_ messages and delegates unrelated queries to super. Its second argument receives respond_to?'s private-method preference. section 15.1.1

Keep these distinctions in mind:

  • Define respond_to_missing? when method_missing handles a family of messages that callers may need to discover. section 15.1.1
  • Let respond_to? invoke the callback; respond_to_missing? is a supplemental helper and is not intended to be called directly. section 15.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines callback behavior, argument forwarding, and method-object visibility without treating the callback as a direct query.
Examples
Uses Person's dynamic set_age setter and verifies it through respond_to? and method.
What it assumes
Assumes method_missing and respond_to?; teaches how dynamic setters become discoverable.
What you can do after
Apply it via Ruby's respond_to? so dynamically handled messages report accurate capabilities.
How it connects
Connects method_missing, respond_to?, method objects, and runtime introspection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.