0.1 Being Meta

Programming Programming

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 foldl to Ruby's native Array class
  • Programmatic method invocation: Use send to 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.

Example Code:

Output Window

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.

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.

Open to Change

Almost every major language construct in Ruby - most notably classes and methods - can be changed at runtime. You can add methods to classes, remove them or redefine them. This is fairly unusual for a mainstream object oriented language.

Example Code:

Output Window

This fails, obviously, because there’s no method called everything_changes. Let’s re-write the program, adding the method to the class by re-opening it.

Example Code:

Output Window

There - as painless as that.

There is no try

As with all our lessons, we believe that the best way to learn is by doing.

Ruby's String has no method that allows you to split a sentence into an Array of words. Let's add a method called words to String to do just this. If you're not sure about how to split a string, take a look at our lesson on string manipulation in the "Ruby Primer" first.

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Srushti