Cover by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required