From: "Chr. Rippel" Date: 2002-01-19T06:59:11+09:00 Subject: Re: dynamic method creation "Albert L. Wagner" wrote in, .... > > >class Record > > > def initialize(name) > > > @name = name > > > end > > >end > > > > > >fieldNames = ['abc', 'dof', 'ghi'] > > >fieldTypes = ['String', 'Fixnum', 'Float'] > > >rec = Record.new('aRecord') > > >class << rec > > >end > > ^^^ > > This 'end' is probably not supposed to be here, right? > > I think it's needed to close the class << rec, just above it. I > get a parse error without it. wierd it should not be necessary - anyway modulo the `case issue' you might be looking at something like this ------ class Record def initialize(name) @name = name end def singleton_attr_writer (*names) singleton_type = class << self; self end # over come the private declaration of attr_writer singleton_type.send (:attr_writer,*names) end end rec = Record.new 'aRecord' fieldNames = ['abc', 'dof', 'ghi'] rec.singleton_attr_writer (*fieldNames) p rec.instance_variables rec.abc= 'a' rec.dof= 1 rec.ghi= 1.0 p rec.instance_variables inst_vars = rec.instance_variables.collect do |var| rec.instance_eval (var) end p inst_vars ----- ["@name"] ["@dof", "@abc", "@name", "@ghi"] [1, "a", "aRecord", 1.0] ----- /Christoph > > > > > >fieldNames.size.times do | i | > > > f = fieldNames[i] > > > defStr = "def rec.#{f}=(obj)\n" > > > case fieldTypes[i] > > > when 'String' then defStr << "@#{f} = obj\n" > > > when 'Fixnum' then defStr << "@#{f} = obj\n" > > > when 'Float' then defStr << "@#{f} = obj\n" > > > end > > What is the purpose of this 'case' statement? All branches seem to do the > > same thing - am I missing something? > > No, you aren't missing anything. Those are fossils from earlier > code. Sorry. > > > > > > defStr << "end\n" > > > puts defStr > > > eval defStr > > Maybe it's better to use instance_eval? > > Like this? > > rec.instance_eval defStr > > That works too. What is the difference? > > > > >end > > ^^^ > > I suspect that this 'end' is the one that corresponds to the > > class << rec above (?) > This one closes: fieldNames.size.times do | i | > > > > >p rec.abc=(nil) > > >p rec.dof=(nil) > > >p rec.ghi=(nil) > > >p rec.methods > > > > I can't come up with another way that doesn't use some kind of eval to do > > this. > > > > Phil > > Thanks, Phil. I think I'll try writing it to a file and then > require it. It shouldn't happen too often. > > -- > "It requires wisdom to understand wisdom: > the music is nothing if the audience is deaf." > - Walter Lippman >