Re.Mark

My Life As A Blog

Ruby Tuesday #16 Part 1 : A Little Light Metaprogramming

leave a comment »

One of the reasons I was interested in learning about Ruby is metaprogramming.  For those new to Ruby, consider the following code:

class Test
 (0..5).each do |i|
    define_method "method_#{i}" do
      puts "Hello World #{i}"
    end
  end
end

Ok, it may not be the most useful piece of code in that form, but I think it shows just how metaprogrammable Ruby is.  When you remember that you can modify classes at runtime, alias methods and so on, the possibilities start to become clear.  If this has got you thinking about metaprogramming and what you could use it to achieve, this post goes into more detail on metaprogramming techniques in Ruby.

Advertisements

Written by remark

July 29, 2008 at 5:36 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: