Ruby Adventures

Optional bonus: DIY Metaprogramming

Parts 1–3 are plenty to chew on, and you can proceed directly to the reflection if you like. If you are having fun with Ruby and looking for something extra fun and uniquely Ruby-esque, here’s a bonus.

Take a look at at the examples in lib/metaprogramming. These two files are (roughly) things I demoed in class:

  • property.rb: A simple example that reproduces Ruby’s built-in attr_accessor using define_method.
  • animal.rb: A more complex example, also using define_method.

Now take a look at number_speller.rb. This is a different sort of beast that uses method_missing, a Ruby feature I haven’t shown in class yet. This example is a bit diabolical. Can you figure out how it works?

Run each example, and study the code alongside the output. You can run one by typing, for example:

ruby lib/metaprogramming/property.rb

With each of these examples, it may be easier to start with the bottom section of the code: look at how the metaprogramming is used first, then look at how it is implemented.

Now, add your own example of metaprogramming to lib/metaprogramming, in a similar spirit as the existing ones. Feel free to steal any of the existing code for your own effort.

What should your example do? Fool around! Be inventive!

Don’t forget to do the reflection when you’re done.