Chapter 8. Reflection and Metaprogramming

image with no caption

We’ve seen that Ruby is a very dynamic language; you can insert new methods into classes at runtime, create aliases for existing methods, and even define methods on individual objects. In addition, it has a rich API for reflection. Reflection, also called introspection, simply means that a program can examine its state and its structure. A Ruby program can, for example, obtain the list of methods defined by the Hash class, query the value of a named instance variable within a specified object, or iterate through all Regexp objects currently defined by the interpreter. The reflection API actually goes further and allows a program to alter its state and structure. A Ruby program can dynamically set named variables, invoke named methods, and even define new classes and new methods.

Ruby’s reflection API—along with its generally dynamic nature, its blocks-and-iterators control structures, and its parentheses-optional syntax—makes it an ideal language for metaprogramming. Loosely defined, metaprogramming is writing programs (or frameworks) that help you write programs. To put it another way, metaprogramming is a set of techniques for extending Ruby’s syntax in ways that make programming easier. Metaprogramming is closely tied to the idea of writing domain-specific languages, or DSLs. DSLs in Ruby typically use method invocations and blocks as if ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.