From: matt@... (matt neuburg) Date: 2006-11-12T05:10:05+09:00 Subject: Re: eval question Peter Szinek wrote: > Hi, > > I am setting up a few variables based on user input with the following > code snippet: > > ================================== > vars = %w{a b c} > > vars.each do |var| > print "#{var} = " > val = gets > eval("$#{var}=#{val.chomp}") > end > > #use a, b, c here for something > ================================== > > What I don't like about this code is the use of global variables. > However, I have to use them - or otherwise a,b,c will be already out of > scope at the place I need them. > > Another possibility would be to use constants, i.e. > > vars = %w{A B C} > > which would work well - however, since I am repeating the process more > times, from the second iteration on I am getting warnings that A, B, C > etc were already initialized, which is not nice. > > I guess yet another possibility would be to wrap a class around this > stuff and use instance_eval or something like that - but a class that > serves solely this purpose looks to heavy to me... > > Any other ideas? Pass a binding? a = 1 b = 2 c = 3 def goforit(w, bind) w.each do |v| eval("#{v} = 'heehee'", bind) end end goforit %w{a b c}, binding puts a, b, c m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Tiger - http://www.takecontrolbooks.com/tiger-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com