AlbertEngelB
AlbertEngelB

Reputation: 16436

Accessing nested hashes using variables

I have a nested hash like so:

someVar = { key1: { key2: 'value' } }

I can access the value by using it in this manner:

someVar[:key1][:key2]

How would I access it using a variable?

hashObj = { key1: { key2: 'value' } }
oneKey = "key1"
twoKey = "key2"

puts hashObj[:key1]            # Works
puts hashObj[:key1][:key2]     # Works

puts hashObj[oneKey]           # Blank
puts hashObj[oneKey][twoKey]   # Error

I'm sure there is a duplicate of this question somewhere, but I can't seem to locate one however.

Upvotes: 0

Views: 93

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

You might find it convenient to write a small method to extract the values you want:

def get_val(h, *keys)
  keys.reduce(h) do |h,k|
    v = h[k]
    return v unless v.is_a? Hash
    v
  end
end

h = { key1: { key2: 'cat' }, key3: { key4: { key5: 'dog' } } } 

get_val(h, :key1, :key2)        #=> "cat"
get_val(h, :key3, :key4, :key5) #=> "dog"

Some error-checking would be needed, should, for example,

get_val(h, :key1, :key2, :key3)

is entered.

Edit: With Ruby 2.3+ you can improve this by using Hash#dig:

def get_val(h, *keys)
  h.dig *keys
end

 get_val(h, :key3, :key4, :key5)
   #=> "dog" 
 get_val(h, :key3, :key4)
   #=> {:key5=>"dog"} 
 get_val(h, :key3, :key4, :key5)
   #=> "dog" 
 get_val(h, :key3, :key5, :key4)
   #=> nil 

Upvotes: 1

Brennan
Brennan

Reputation: 5732

Your keys are symbols, and you are trying to accessing them using strings. Turn them into symbols:

puts hashObj[oneKey.to_sym][twoKey.to_sym]

Upvotes: 4

Related Questions