Metaprogramming. What a lovely buzz word. I guess I’ve heard it enough and knew what the short definition is. Metaprogramming is code that writes code. I think it is one of those things I just never thought about, even though I had used concepts and even written some before without realizing it until recently.
Here is a short and simple example.
class Something
@my_hash = {"foo" => "1234", "bar" => "5678"}
def initialize
@my_hash.each do |a, b|
self.instance_eval do
define_method(a.to_s) {b.to_s}
end
end
end
end
And now we can play with it.
a = Something.new a.foo # => 1234 a.bar # => 5678
Now, what happened here is pretty neat in my opinion. We took our hash, my_hash, and in our initialize method, created two instance methods from its values. define_method is what did all the magic. You need to pass it a proc or, like what I did, just give it a simple block (just the string value from my hash).
Pretty neat, eh?
-
1
Pingback on Nov 8th, 2008 at 5:32 am
[...] public links >> metaprogramming Simple Meta Programming in Ruby Saved by lioninside on Fri 07-11-2008 write pretty words Saved by andrezera on Wed 22-10-2008 [...]
Leave a Comment
Latest Entries
- Zip Code Distance Searching in Ruby on Rails
- Smart Searching Using Anonymous Scopes
- Yes, I started a dating site. I’m sorry.
- I’ve pulled a Brett Farve
- blog.john.yerhot.org
- Deployment Nightmare: Godaddy
- KVM, VMware, and my whole Saturday
- Henry Rollins at Sacred Heart
- Obligatory Google Chrome Post
- rQuote - Ruby on Rails Stock Quote Plugin
Oct 9th, 2008 at 1:49 pm
Good example. One typo though. “We took our hash, my_has,” should be “We took our hash, my_hash,”. Thanks for the example and simple introduction to metaprogramming.