我有一长串不知名的字符串(但最多可以说是5)。我还有一个空哈希h = {}
和一个值。
我想将数组和值转换为哈希,如下所示:
val = 1
h = {}
a = ['a', 'b', 'c', 'd']
# result I want:
{
'a' => {
'b' => {
'c' => {
'd' => 1
}
}
}
}
重要的是,某些密钥可能已经存在(之前在循环迭代中创建)。所以我可能会:
val = 2
h = {'a' => {'b' => {'c' => {'d' => 1}}}}
a = ['a', 'b', 'c', 'e']
# result I want:
{
'a' => {
'b' => {
'c' => {
'd' => 1,
'e' => 2
}
}
}
}
关于如何做到这一点的任何想法?
答案 0 :(得分:4)
再一次,inject
救援:
def dredge(hash, list, value = nil)
# Snip off the last element
*list, tail = list
# Iterate through the elements in the path...
final = list.inject(hash) do |h, k|
# ...and populate with a hash if necessary.
h[k] ||= { }
end
# Add on the final value
final[tail] = value
hash
end
这可以稍微改进,具体取决于您需要在零长度列表等方面的弹性。
这里适用:
h = {}
a = ['a', 'b', 'c', 'd']
dredge(h, a, 1)
# => {"a"=>{"b"=>{"c"=>{"d"=>1}}}}
h = {'a' => {'b' => {'c' => {'d' => 1}}}}
a = ['a', 'b', 'c', 'e']
dredge(h, a, 2)
# => {"a"=>{"b"=>{"c"=>{"d"=>1, "e"=>2}}}}