开发者

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}}}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜