From: Michael Witrant Date: 2001-06-21T21:55:09+09:00 Subject: [ruby-talk:16701] Re: cgi.rb cookie access On Thu, 21 Jun 2001 08:40:45 +0900 "HarryO" wrote: > Say I have two variables called "name" and "value". Is the correct way > to create a variable with the given name and value, to use eval, as in ... > > eval "#{name} = #{value}" > > or is there a better/cleaner way to do this? > Actually, I think it won't work, because the variable is created in the eval binding, and is not exported to your local binding. You must assign it before eval, but since you must use eval to initialize it, you can't. You can if a method exists to create local variable, but I don't think so. But you can create instance variables if you want: eval "@#{name} = #{value.inspect}" Another approach I often use in this case is to use a special hash that allow acces to values through methods. For example: h = Structash.new # I didn't find a better name for it.. h[:toto] # => nil h.toto # => nil h.toto = 1.5 h.toto # => 1.5 h[:toto] # => 1.5 # In your case: name = "titi" value = "tata" h[name.intern] = value h.titi # => "tata" h[:titi] # => "tata" You can access values by using methods, so that your hash looks like a struct. Implementing that is quite easy: class Structash < Hash def method_missing(symbol, *args, &block) method = symbol.id2name if method[-1].chr == "=" symbol = method[0..-2].intern raise "Cannot set #{symbol.id2name}: a method with that name already exists" if respond_to? symbol self[symbol] = args[0] else if has_key? symbol self[symbol] else #raise NameError, "undefined local variable, method or key '#{symbol.id2name}' for #{inspect}" default end end end end In my scripts, I often use that as the default behavior of Hashes. Mike. midulo.