From: "Albert L. Wagner" Date: 2002-01-19T05:47:21+09:00 Subject: Re: dynamic method creation Phil Tomson wrote: > > In article <3C4878FE.F0D83753@uark.edu>, > Albert L. Wagner wrote: > >I have a need to dynamically create methods with method names > >that are not known until run time. Below is my current best > >shot. Is there a better way? If methods allowed expressions as > >names, and not just as qualifiers, I wouldn't need the eval. > > A couple of questions about your example.... > > > > >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. > > >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