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. Carl

    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.

  1. 1 Recent Links Tagged With "metaprogramming" - JabberTags

    [...] 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


To insert code, wrap in <pre></pre> tags.



Recommend Me

John Yerhot is Digg proof thanks to caching by WP Super Cache!