From: Asfand Yar Qazi Date: 2005-02-18T06:04:53+09:00 Subject: Re: Evaluating a string of Ruby code within an anonymous module: done correctly? Joel VanderWerf wrote: > Joel VanderWerf wrote: > >> Here's an even simpler way, just wrapping the code in a proc, which >> may be suitable for small snippets of code: >> >> def eval_string(s, *args_to_pass) >> pr = eval("proc do |*args| #{s.to_str} end") >> pr[*args_to_pass] >> end >> >> eval_string(<> b = args.collect {|i| i*3} >> c = b.join("||") >> puts(c) >> EOL >> >> Warning: the binding of the "pr" local variable and the two arg >> variables is still in effect wthin the proc, so this may not be >> suitable. Or you could use very obscure names and hope. > > > Just realized how to fix that: > > def empty_binding > binding > end > > def eval_string(s, *args_to_pass) > pr = eval("proc do |*args| #{s.to_str} end", empty_binding) > pr[*args_to_pass] > end > > eval_string(< b = args.collect {|i| i*3} > c = b.join("||") > puts(c) > #p pr #<-- now this fails > EOL > > I think I like this method best. very nice! Thanks