我有一个包含大量嵌套键值对的大哈希。 例如。
h = {"foo" => {"bar" => {"hello" => {"world" => "result" } } } }
现在我想访问 result
并且我在数组中有按正确顺序排列的键。
keys_arr = ["foo", "bar", "hello", "world"]
动机很明确,我想做的是:
h["foo"]["bar"]["hello"]["world"]
# => "result"
但是我不知道该怎么做。我目前正在做:
key = '["' + keys_arr.join('"]["') + '"]'
eval("h"+key)
# => "result"
这看起来像是黑客攻击。它还大大降低了我在真实环境中使用哈希的能力。
请提出替代和更好的方法。
最佳答案
使用 Enumerable#inject
(或 Enumerable#reduce
):
h = {"foo" => {"bar" => {"hello" => {"world" => "result" } } } }
keys_arr = ["foo", "bar", "hello", "world"]
keys_arr.inject(h) { |x, k| x[k] }
# => "result"
更新
如果你想做这样的事情:h["foo"]["bar"]["hello"]["world"] = "ruby"
innermost = keys_arr[0...-1].inject(h) { |x, k| x[k] } # the innermost hash
innermost[keys_arr[-1]] = "ruby"
关于ruby - 使用数组中的键访问散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25647410/