From: Ashley Moran Date: 2007-10-13T21:41:55+09:00 Subject: Re: Generation of initialize On Oct 13, 2007, at 1:20 pm, arcadiorubiogarcia@gmail.com wrote: > Hi everyone, > > I'm new to Ruby. I'm looking for an elegant solution to a simple > problem. > > I have some classes like this one in my code: > > > class A > > attr_reader :a1, a2 > > def initialize(a1, a2) > @a1 = a1 > @a2 = a2 > end > > end > > > I'm looking for a way in order not to have to define the initialize > method in each class. Struct doesn't fit my needs since due to single > inheritance I can't have any other superclass, and I would like to. > > Any suggestions? > > Thanks in advance. > > Hi Don't know if this has been done before, but here's a quick stab I took at it: require 'generator' module InitializesWith def initializes_with(*params) define_method :initialize do |*args| iterator = SyncEnumerator.new(params, args) iterator.each do |param, arg| instance_variable_set "@#{param}", arg end end end end class Class include InitializesWith end class C attr_reader :x, :y, :z initializes_with :x, :y, :z end obj = C.new(1,2,3) obj.x # => 1 obj.y # => 2 obj.z # => 3 Any good? Ashley -- blog @ http://aviewfromafar.net/ linked-in @ http://www.linkedin.com/in/ashleymoran currently @ home