Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access nested hash element specified by an array of keys [duplicate]

Tags:

arrays

ruby

hash

I'm trying to get a general solution to the problem of accessing an element in a nested hash given an array of key values,e.g.:

hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

function(array)
=> "foo"

I'm guessing this could be a one-liner. It also is quite closely related to this problem: Ruby convert array to nested hash

like image 249
waferthin Avatar asked Aug 15 '13 11:08

waferthin


People also ask

How do I access nested hash?

Accessing a specific element in a nested hash is very similar to a nested array. It is as simple as calling hash[:x][:y] , where :x is the key of the hash and :y is the key of the nested hash.

What is a nested hash?

Nested hashes allow us to further group, or associate, the data we are working with. They help us to deal with situations in which a category or piece of data is associated not just to one discrete value, but to a collection of values.

What is a hash in ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.


1 Answers

hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"
like image 175
Arup Rakshit Avatar answered Sep 18 '22 12:09

Arup Rakshit