5. Metaprogramming

In Ruby, everything is open to modification at run time. Classes, modules, and even the behavior of individual objects can all be changed while a program is running. It’s trivial to write code which defines new classes or adds methods to an existing class or object. Virtually nothing is off-limits. This so-called “metaprogramming” is one of Ruby’s most powerful features. It’s also one of its most dangerous.

There are a lot of good uses for metaprogramming. Cleaning up redundant code, generalizing a feature to work with more than one class, and creating domain specific languages are just a few examples. But there are downsides too. Methods like eval tend to become a crutch since they can be used to solve so many programming ...

Get Effective Ruby: 48 Specific Ways to Write Better Ruby 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.