This is a very brief article about one great feature of the Ruby language - dynamically adding methods to classes at runtime.
Basically I have been learning the Ruby language and thought I would share few snippets with people in small articles, so if you are not familiar with Ruby take a quick look and see what you think - you never know it might spark your interest!
Adding methods to class instances
One great feature of Ruby is that it allows you to add methods to individual class instances on the fly. The code is pretty self explanatory so I won't go into any details.
Update - 15 Sep 2006
- In response to some comments regarding how you use reflection etc in ruby I have added a new block of code showing how to reflect against a class, call methods dynamically and a simple benchmark showing the timings for each method.
## ---- Add methods to a class instance at runtime. ---- ##
# Create a very simple class.
<CODE __designer:dtid="281474976710672">class TestAddMethod
puts "Method1 Called."
There are other ways to add methods to classes - one is to use a mix-in - where you essentially include all of the methods from a module in a class definition. This allows you to mimic some of the multiple inheritance functionality seen in C++.
Anyway - thanks for your time. Any comments/questions are welcome. As I play with Ruby more I will try to post more articles on things that I find interesting.