【问题标题】:Access nested hash element specified by an array of keys [duplicate]访问由键数组指定的嵌套哈希元素[重复]
【发布时间】:2013-08-15 11:08:06
【问题描述】:

我正在尝试为给定键值数组访问嵌套哈希中的元素的问题找到一个通用解决方案,例如:

hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

function(array)
=> "foo"

我猜这可能是单线。它也与这个问题密切相关: Ruby convert array to nested hash

【问题讨论】:

  • 我没发现 - 哎呀
  • 你给的链接..太棒了..我从中学到了一个新概念..感谢您发现它... :)

标签: ruby arrays hash


【解决方案1】:
hash = { "a" => { "b" => 'foo' }}
array = ["a", "b"]

array.inject(hash,:fetch)
# => "foo"
array.inject(hash,:[])
# => "foo"

【讨论】:

  • 谢谢!如果它对其他人有帮助,我在寻找与 Clojure 的 get-in 等效的 Ruby 时遇到了这个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2011-03-22
  • 2013-12-06
  • 2013-11-01
  • 2013-03-22
相关资源
最近更新 更多