From: Trans Date: 2007-10-13T21:41:38+09:00 Subject: Re: Generation of initialize On Oct 13, 5:20 am, arcadiorubiogar...@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? You could create an attr_initializer, something like: module MyInitSystem # extend hack def self.included(base) base.extend ClassMethods end module ClassMethods attr_reader :attr_initializers def attr_initializer(*args) @attr_initializers ||= [] @attr_initializers.concat(args) attr_reader *args end end def initialize(*args) self.class.attr_initializers.each_with_index do |a,i| instance_variable_set("@#{a}", args[i]) end end end class A include MyInitSystem attr_initializer :a, :b end Albeit, I'd use a hash to populate my object by var name. T.