liveBook · Manning

Reflection

As explained in The Well-Grounded Rubyist, Fourth Edition

Introspection, also called reflection, is the examination of a program's objects, methods, or state while the program is running.

Reflection, also called introspection, examines a running Ruby program: objects can be asked about their methods, variables, state, and capabilities while execution continues. section 2.3.2 section 7.7

Check before sending a message

Calling an unknown message raises NoMethodError. A conditional check makes the interaction explicit: `if obj.respond_to?("talk"); obj.talk; else; puts "Sorry, the object doesn't understand the 'talk' message."; end`. `respond_to?` exists for every object and answers whether it currently handles a named message. section 2.3.2

Ruby reflection can inspect several layers of a running program:

  • Ask objects which methods they can execute; class and module objects can expose methods available to their instances or through inclusion. section 7.7
  • Inspect local and global variables, instance variables, class variables, and constants accessible at a particular runtime point. section 15.3
  • Examine stack traces, including the method calls, filenames, and line numbers leading to an event. section 15.0
  • Combine method queries with dynamic facilities such as `method_missing` and `respond_to_missing?` when handling unrecognized messages. section 15.6

Reflection is both passive inspection and a practical design tool. It supports capability checks, dynamic message handling, debugging, and code that reacts to runtime events; the available information depends on the object and the moment of inspection. section 7.7 section 15.0 section 15.6

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains capability checks, method and variable listings, constants, stack traces, and dynamic message hooks without exhaustive API detail.
Examples
Demonstrates respond_to? before calling talk, method inspection, variable and constant listings, and stack-trace queries.
What it assumes
Assumes familiarity with Ruby objects, methods, messages, classes, and modules while introducing runtime inspection as a language capability.
What you can do after
Apply it via Ruby reflection methods to check capabilities, inspect runtime state, handle dynamic messages, and diagnose execution paths.
How it connects
Connects reflection with objects, methods, classes, modules, message dispatch, callbacks, method_missing, constants, and stack traces.

Also explained in

Compare how 13 books explain reflection →

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.