开发者

Ruby convert array to nested hash

开发者 https://www.devze.com 2023-02-13 04:28 出处:网络
I have the following: value = 4开发者_JS百科2 array = [\"this\",\"is\",\"a\",\"test\"] how can I convert that to get this

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

精彩评论

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

关注公众号