From: Axel Etzold Date: 2007-06-05T05:03:31+09:00 Subject: Re: Help needed: Dynamically create a Proc from a String and evaluate it Dear Jason, thank you for responding. Here is what I have so far ( I hope the formatting won't be destroyed): class String def generate_formula # left-hand side of equation gives the function f=self.split(/\=/) formula='def ' + f[0] args=f[1].gsub(/[^\+\-\*\/]+\(/,'').gsub(/\)/,'').split(/[\/\*\-\+]/).uniq args_new=args.collect{|x| if x==x.capitalize ; x='_' + x; else x=x; end} rhs=f[1] lhs=f[0] args.each_with_index{|x,i| if args_new[i]!=x lhs.gsub!(x,args_new[i]) rhs.gsub!(x,args_new[i]) end } formula='def ' + lhs + "\n" #formula<<'p ' + lhs #formula<<'p ' + rhs formula<<"\n return Proc.new{|" + args_new.join(',') + '| ' formula<< rhs + ' }' formula<<"\n end \n" name=f[0][0...f[0].index('(')] # return the following: # 1) formula=String containing Proc method to be evaluated # 2) name of the Proc method # 3) Array of arguments ( variables and constants occurring # in the original formula # 4) arguments from 3) changed to non-uppercase, if needed return formula,name,args,args_new end def eval_formula(hash) f,name,vars,new_vars=self.generate_formula # do this to change uppercase variables, if needed hash2={} hash.each{|k,v| ind=vars.index(k) if v.class!=Array v=[v] end hash2.store(new_vars[ind],v) } # generate string for Proc to be evaluated ind1=f.split(/\n/)[0].index('(') ind2=f.split(/\n/)[0].index(')') args_left=f.split(/\n/)[0][ind1+1...ind2] other_args=new_vars-args_left.split(',') eval_fn = name + '(args_left)' max_nr_of_vals=[] # how many evaluations ? # to do: check that number of changed values # is either 1 or coincides for all variables hash2.values.each{|x| max_nr_of_vals<1 this_val=hash2[my_var][k] # several values of "constants" else this_val=hash2[my_var][0] # just one value end ev_hash_text<