From: Robert Klemme Date: 2004-03-30T21:54:25+09:00 Subject: Re: Attr_constructor "Daniel Sheppard" schrieb im Newsbeitrag news:EE0A2C5DE8D7CA4792891604D4FED52E016749EB@mlbmail.pronto.com.au... > I've been writing a couple of very struct-like classes, and got annoyed > at having to write: > > class MyStructLikeThing > attr_accessor :one, :two, :three, :four, :five > def initialize (one, two, three, four, five) > @one, @two, @three, @four, @five = one, two, three, four, five > end > end > > And how ugly that looked in the code, so I decided to try my hand at > whipping up an attr_constructor statement. > > class Module > private > def attr_constructor(*args) > self.class_eval %Q{ > def initialize(#{args.join(', ')}) > #{args.collect{ |setting| > "instance_variable_set(\"@#{setting}\", #{setting})" }} > end > } > end > end > > class MyStructLikeThing > attr_accessor :one, :two, :three, :four, :five > attr_constructor :one, :two, :three, :four, :five > end > > It strikes me as a little cludgy. Is there a better way of doing this? Well, you could at least save the attr_accessor line for those fields contained in the constructor: class Module private def attr_constructor(*args) self.class_eval %Q{ def initialize(#{args.join(', ')}) #{args.collect{ |setting| "@#{setting} = #{setting}\n" }} end } args.each do |sym| attr_accessor sym end end end class MyStructLikeThing attr_constructor :one, :two, :three, :four, :five end mst = MyStructLikeThing.new 1,2,3,4,5 > Is there a way to get the args variable so that it can be read from > within a module_eval block? > > (Note also, that I know about the Struct module, this is just a > simplified example) Why don't you use Struct then? You can add arbitrary methods after creating the struct like this: MyStruct = Struct.new( :one, :two, :three, :four, :five ) class MyStruct def test p "test" end end Regards robert