Metaprogramming is the act of writing code that operates on code rather than on data. This involves inspecting and modifying a program as it runs using constructs exposed by the language.
In the example below, here are some of the "meta" changes we're making to the program:
- Reopening classes: Add a method named
foldlto Ruby's native
- Programmatic method invocation: Use
sendto call a method by name programmatically
The end result is the ability to combine the elements of any array containing any type of object in fairly arbitrary ways.
Metaprogramming is supported across many languages using many different techniques; you’ve probably used some of them already. Here’s a brief list of some popular languages besides Ruby that support metaprogramming in some form.
- Lisp via homoiconicity
- Java via reflection
- C# via reflection
The focus of this book is to demonstrate how metaprogramming happens in Ruby, what its limitations are and what kinds of problems are best solved using it.
This last is pretty important, because metaprogramming is arguably one of the most misused features of the Ruby language. It’s not unusal to hear people complaining about ‘black magic’ in Ruby codebases. This is usually because they, or the author of that codebase, or both didn’t understand metaprogramming.
Learning when metaprogramming is the right tool for the job will be of considerable value to you in creating powerful yet maintainable codebases.