ruby - 使用数组中的键访问散列

标签 ruby arrays hash ruby-1.8.7

我有一个包含大量嵌套键值对的大哈希。 例如。

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/

相关文章:

c++ 填充现有 C 数组的边

perl - 实现调度表

perl - perl 的每个功能都值得使用吗?

ios - 从项目 IOS 的 AnyObject 列表中获取索引

ruby - ruby 中的 thread.exit 和 thread.pass 有什么区别?

ruby - 在 Sinatra 应用程序中维护单一、持久的 EM 连接

ruby - Ruby 中 Math Power (**) 的反面是什么?

java - 当我猜错单词时,为什么我的菜单不显示?

perl - 是否支持散列上的 postderef 语法?

ruby - ActiveRecord 连接警告。 (数据库连接不会自动关闭)