From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2002-01-19T05:19:02+09:00 Subject: Re: dynamic method creation 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? >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? > defStr << "end\n" > puts defStr > eval defStr Maybe it's better to use instance_eval? >end ^^^ I suspect that this 'end' is the one that corresponds to the class << rec above (?) >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