ruby - create nested hash from a list -


i have got list l = [:foo, :bar, :baz] , want assign varible hash h ={} programmatically.

hash should like

{ foo: { bar: { baz: some_value } } } 

note: keys variables!

question:

  1. how can this?

you use inject on reversed list :

l = [:foo, :bar, :baz] h = l.reverse.inject(:some_value) |value, key|   { key => value } end p h # {:foo=>{:bar=>{:baz=>:some_value}}} 

reverse used in order build innermost hash first, , keep building nested hash outwards.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -