Posts Tagged ‘Metaprogramming’

Simple Meta Programming in Ruby

Sunday, August 10th, 2008

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?