Using variables for the hash name and key name

I’m trying to call a value from a hash using variables for both the hash
name and the key I’m trying to call

So I’ve got a hash like this

hash_name = {
“key_name_1” => “value_name_1”,
“key_name_2” => “value_name_2”,
“key_name_3” => “value_name_3”,
}

and earlier in the script I have two variables:

@hash_name_var, which looks like it’s equal to hash_name

(this statement is true, ‘hash_name’ == @hash_name_var)

@key_name_var, which looks like it’s equal to key_name_1

(this statement is true, ‘key_name_1’ == @key_name_var)

So, I’m trying to get the value out of the hash with

@hash_name_var[@key_name_var]

but this doesn’t work

However, hash_name[@key_name_var] does work, so since
‘hash_name’ == @hash_name_var it makes me think I need to find
a way to make:

@hash_name_var == hash_name

instead of

@hash_name_var == ‘hash_name’

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.

IMHO, the question you asked generally comes from Perl programmers
who are trying to emulate Perl’s reference data type in Ruby. That
is almost always the wrong approach in Ruby.

Gary W.

On Thu, May 10, 2007 at 03:56:15AM +0900, Gary W. wrote:

@hash_name = ‘hash1’
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)