【发布时间】:2014-09-03 14:48:59
【问题描述】:
我有一个包含大量嵌套键值对的大哈希。 例如。
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"
这看起来像一个黑客。它也大大降低了我在真实环境中使用哈希的能力。
请提出替代和更好的方法。
【问题讨论】:
标签: ruby arrays hash ruby-1.8.7