使用扩展参数从多维哈希中获取值

3

我无法找到一种好的方式来使用splat操作符访问一个多维哈希表中提供的键名 - 有什么建议吗?

例如:我有一个哈希表如下:

{
  'key' => 'value',
  'some' => {
     'other' => {
         'key' => 'othervalue'
     }
  }
}

一个函数定义def foo(*args)

我想要返回foo('key')valuefoo('some','other','key')othervalue。我所能想到的只有一些相当冗长丑陋的for循环,还有很多nil?检查,并且某种程度上我确信我错过了更ruby式的方法来做到这一点简短简洁。任何提示都将不胜感激。

更新

使用下面Patrick的答复,我得出了结论

def foo(hash, *args) 
  keys.reduce(hash, :fetch)
end

它的功能符合我的预期。谢谢!

1个回答

9

在其他一些语言中,这被称为get_in,例如在ClojureElixir中。以下是Ruby中的函数式实现:

class Hash
  def get_in(*keys)
    keys.reduce(self, :fetch)
  end
end

使用方法:

h = {
  'key' => 'value',
  'some' => {
    'other' => {
      'key' => 'othervalue'
    }
  }
}

h.get_in 'some'
#=> {
#     "other" => {
#       "key" => "othervalue"
#     }
#   }

h.get_in 'some', 'other'
#=> {
#     "key" => "othervalue"
#   }

h.get_in 'some', 'other', 'key'
#=> "othervalue"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接