From: Joel VanderWerf Date: 2006-11-12T04:02:12+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. Use a hash? vars = { "a" => nil, "b" => nil, "c" => nil, } def get_input vars vars.keys.each do |var| print "#{var} = " val = gets vars[var] = val.chomp eval("$#{var}=#{val.chomp}") end end get_input vars p vars __END__ a = 1 b = 2 c = 3 {"a"=>"1", "b"=>"2", "c"=>"3"} You can use instance_eval with the hash, as you suggested: module AcessibleKeys def method_missing(m, *rest) if rest.empty? fetch(m.to_s) else super end end end vars.extend AcessibleKeys get_input vars p vars vars.instance_eval do puts "a+b+c = #{a+b+c}" end __END__ a = 1 b = 2 c = 3 {"a"=>"1", "b"=>"2", "c"=>"3"} a+b+c = 123 -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407