From: Michael Neumann Date: 2004-11-22T21:49:24+09:00 Subject: Re: Typical/idiomatic examples of dynamic code generation with Ruby? Iwan van der Kleyn wrote: > Hi there, > > I'm writing a paper on the "rediscovery of dynamic languages". > Definition issues aside (what *is* a "dynamic" language, anyway?), in > it I try to show how "old" (Smalltalk, Lisp) and "new" (Python, Ruby) > programming languages are vastly superior for the cost-effective > development of scalable and secure applications compared with static > languages like C/C++ and half-breeds like Java and C#. Nothing > original for sure, but then I again I'm trying to postulate some > convincing arguments for a non-geek, managerial audience. > > In the paper I'm comparing "idiomatic" examples of how these languages > deal with common problems. Problem is, I'm quite new with Ruby and I'm > a bit at a loss for examples on how to show Ruby's strengths with > dynamic code generation (metaprogramming). That is often mentioned as > one of Ruby's strengths. Don't get me wrong, I've found that Ruby has > got the necesarry nuts and bolts but I couldn't really figure out what I > could do with it, what I could not easily do with Python as well. > > So my question: do you know of any examples on the subject of dynamic > code generation which would be typical for Ruby and could not be > easily implemented in languages like Python? I think stuff like "attr_accessor" is typical for Ruby. It could be implemented like this: class Module def attr_accessor(*attrs) attrs.each do |attribute| class_eval "def #{ attribute }() @#{ attribute } end" class_eval "def #{ attribute }=(val) @#{ attribute } = val end" end end end # and use it class MyClass attr_accessor :a def initialize @a = "test" end end m = MyClass.new p m.a # => "test" m.a = 2 p m.a # => 2 You can do the same for defining abstract methods: class Module def abstract(*meths) meths.each do |meth| class_eval "def #{ meth }(*args, &block) raise 'abstract method' end" end end end And for much more else. Have a look at ActiveRecords, which uses quite a lot of metaprogramming, I guess. Regards, Michael