Evaluation Time

Say you have a (Ruby) class, and you start creating a bunch of sub-classes. You want each sub-class to have a set of methods, but because they all look similar it’s uber repetitive. So, how can you define those methods on the fly?

class_eval is one option: it takes a string and evaluates it as code. Given this, you can define a generic method-creator in the superclass which takes a few arguments, and call it with every new sub-class. Hey presto, free methods!

Or you can use define_method, which is slightly neater: just pass in a name and a block which will act as the function code.