From: Ryan Pavlik Date: 2003-07-19T13:32:04+09:00 Subject: Solution (Re: Default constructor) On Sat, 19 Jul 2003 11:03:01 +0900 Pablo Lorenzzoni wrote: > Hello! > > class Klass > attr_accessor :att1, :att2 > def initialize(att1, att2) > @att1 = att1 > @att2 = att2 > end > .... > end > > Is it just me or the construction above is rather common? Is there such a > thing as a default cosntructor? Something that could turn that into > Yes it is. It's pretty easy to add, too, if you think Lisp. This is a little ugly... macros would make this WAY nicer... but here we go: def definit(*args, &block) s = "" args.each { |a| s << "@#{a.to_s} = #{a}\n" } arglist = args.join(', ') module_eval <<-END class << self; attr_reader :_post_init; end @_post_init = block def initialize(#{arglist}) #{s} instance_eval &self.class._post_init if self.class._post_init end END end #m:definit And of course, it wouldn't be complete without an example: class A attr_accessor :a, :b definit(:a, :b) { @a += 1 } def show; p @a, @b; end end #c:A a = A.new(1, 2) a.show This is why macros are cool. Code that writes code is so extremely useful. ;-) (Note: I'm using 1.8 CVS, this may not work in 1.6.) -- Ryan Pavlik "Elfland? Mo' like pansyland." - 8BT