在任意深度访问嵌套哈希值的最红宝石方法是什么?

JD.*_*JD. 8 ruby hash hash-of-hashes

给出如下的哈希:

AppConfig = {
  'service' => {
    'key' => 'abcdefg',
    'secret' => 'secret_abcdefg'
  },
  'other' => {
    'service' => {
      'key' => 'cred_abcdefg',
      'secret' => 'cred_secret_abcdefg'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下我需要一个函数来返回服务/密钥,在其他情况下我需要其他/ service/key.一种简单的方法是传入散列和一组键,如下所示:

def val_for(hash, array_of_key_names)
  h = hash
  array_of_key_names.each { |k| h = h[k] }
  h
end
Run Code Online (Sandbox Code Playgroud)

这样调用会产生'cred_secret_abcdefg':

val_for(AppConfig, %w[other service secret])
Run Code Online (Sandbox Code Playgroud)

看起来应该有比我在val_for()中编写的更好的方法.

tok*_*and 9

def val_for(hash, keys)
  keys.reduce(hash) { |h, key| h[key] }
end
Run Code Online (Sandbox Code Playgroud)

如果找不到某个中间键,这将引发异常.另请注意,这完全相同keys.reduce(hash, :[]),但这可能会让一些读者感到困惑,我会使用该块.


saw*_*awa 6

%w[other service secret].inject(AppConfig, &:fetch)
Run Code Online (Sandbox Code Playgroud)