Access to the nested hash element specified by the key array

I am trying to get a general solution to the problem of accessing an element in a nested hash given by an array of key values, for example:

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

I guess it could be single line. This is also pretty closely related to this problem: Ruby converts the array to a nested hash

+4
source share
1 answer
 hash = { "a" => { "b" => 'foo' }} array = ["a", "b"] array.inject(hash,:fetch) # => "foo" array.inject(hash,:[]) # => "foo" 
+11
source

Source: https://habr.com/ru/post/1497219/


All Articles