Ruby 将数组转换为嵌套哈希 [英] Ruby convert array to nested hash
本文介绍了Ruby 将数组转换为嵌套哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下几点:
value = 42
array = ["this","is","a","test"]
我怎样才能把它转换成这个
how can I convert that to get this
{ "this" => { "is" => { "a" => { "test" => 42 } } } }
数组总是平坦的.
谢谢!
推荐答案
试试这个:
array.reverse.inject(value) { |assigned_value, key| { key => assigned_value } }
#=> {"this"=>{"is"=>{"a"=>{"test"=>42}}}}
这篇关于Ruby 将数组转换为嵌套哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文