如何将 fetch 方法用于嵌套哈希? [英] How do I use the fetch method for nested hash?

查看:36
本文介绍了如何将 fetch 方法用于嵌套哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下哈希:

hash = {'name' => { 'Mike' => { 'age' => 10, 'gender' => 'm' } } }

我可以通过以下方式访问年龄:

I can access the age by:

hash['name']['Mike']['age']

如果我使用 Hash#fetch 方法?如何从嵌套哈希中检索密钥?

What if I used Hash#fetch method? How can I retrieve a key from a nested hash?

正如 Sergio 所提到的,这样做的方法(不为自己创造一些东西)是通过一系列 fetch 方法:

As Sergio mentioned, the way to do it (without creating something for myself) would be by a chain of fetch methods:

hash.fetch('name').fetch('Mike').fetch('age')

推荐答案

现在有一种内置方式,请参阅 this回答.

there is a built-in way now, see this answer.

我所知道的没有内置方法.我目前的项目中有这个

There is no built-in method that I know of. I have this in my current project

class Hash
  def fetch_path(*parts)
    parts.reduce(self) do |memo, key|
      memo[key.to_s] if memo
    end
  end
end

# usage
hash.fetch_path('name', 'Mike', 'age')

您可以轻松修改它以使用 #fetch 而不是 #[](如果您愿意).

You can easily modify it to use #fetch instead of #[] (if you so wish).

这篇关于如何将 fetch 方法用于嵌套哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆