Ruby convert array to nested hash
I have the following:
value = 4开发者_JS百科2
array = ["this","is","a","test"]
how can I convert that to get this
{ "this" => { "is" => { "a" => { "test" => 42 } } } }
the array is always flat.
Thank you!
Try this:
array.reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
#=> {"this"=>{"is"=>{"a"=>{"test"=>42}}}}
精彩评论