From: Brian Candler Date: 2007-05-10T05:57:55+09:00 Subject: Re: using variables for the hash name and key name On Thu, May 10, 2007 at 03:56:15AM +0900, Gary Wright wrote: > > On May 9, 2007, at 1:59 PM, Skye Weir-Mathews wrote: > >So, I'm trying to get the value out of the hash with > > > >@hash_name_var[@key_name_var] > > The short answer is "don't do that". > > If you need to select a particular hash dynamically, then > simply use another hash as an index: > > master = { 'hash1' => { 'a' => 1 }, > 'hash2' => { 'a' => 2, 'b' => 3} > } > > puts master['hash1']['a'] # => 1 > puts master['hash2']['b'] # => 3 > > Of course you can use an instance variable to > select a hash: > > @hash_name = 'hash1' > puts master[@hash_name].inspect # {'a' => 1} > > There are other possibilities. If you are only selecting between > a couple hashes: > > hash = case @select_hash > when 'hash1' then @hash1 > when 'hash2' then @hash2 > end > > puts hash.inspect # this will be @hash1 or @hash2 > > If for some reason these technique doesn't work you'll have > to start playing around with eval to get the indirection > you are looking for. Or if the values are in instance variables, you can use instance_variable_get. @a = "one" @b = "two" which = "@a" puts instance_variable_get(which)