Ruby - 访问多维哈希并避免访问 nil 对象 [英] Ruby - Access multidimensional hash and avoid access nil object

查看:19
本文介绍了Ruby - 访问多维哈希并避免访问 nil 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Ruby:IF 语句中的 Nils
有没有一种干净的方法可以避免在嵌套的参数哈希中调用 nil 上的方法?

假设我尝试访问这样的哈希:

Let's say I try to access a hash like this:

my_hash['key1']['key2']['key3']

如果 key1、key2 和 key3 存在于散列中,这很好,但如果 key1 不存在怎么办?

This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn't exist?

然后我会得到 NoMethodError: undefined method [] for nil:NilClass.没有人喜欢这样.

Then I would get NoMethodError: undefined method [] for nil:NilClass. And nobody likes that.

到目前为止,我通过以下条件处理这个问题:

So far I deal with this doing a conditional like:

if my_hash['key1'] &&my_hash['key1']['key2'] ...

这样合适吗,还有其他 Rubiest 方法吗?

Is this appropriate, is there any other Rubiest way of doing so?

推荐答案

有很多方法.

如果您使用 Ruby 2.3 或更高版本,则可以使用 挖掘

If you use Ruby 2.3 or above, you can use dig

my_hash.dig('key1', 'key2', 'key3')

很多人坚持使用纯 ruby​​ 并链接 && 保护测试.

Plenty of folks stick to plain ruby and chain the && guard tests.

您可以使用标准库 Hash#fetch 也是:

You could use stdlib Hash#fetch too:

my_hash.fetch('key1', {}).fetch('key2', {}).fetch('key3', nil)

有些人喜欢链接 ActiveSupport 的 #try 方法.

Some like chaining ActiveSupport's #try method.

my_hash.try(:[], 'key1').try(:[], 'key2').try(:[], 'key3')

其他人使用andand

myhash['key1'].andand['key2'].andand['key3']

有些人认为 以自我为中心的 nils 是一个好主意(尽管如果有人发现你这样做,他们可能会追捕你并折磨你).

Some people think egocentric nils are a good idea (though someone might hunt you down and torture you if they found you do this).

class NilClass
  def method_missing(*args); nil; end
end

my_hash['key1']['key2']['key3']

您可以使用 Enumerable#reduce(或别名注入).

You could use Enumerable#reduce (or alias inject).

['key1','key2','key3'].reduce(my_hash) {|m,k| m && m[k] }

或者也许使用嵌套查找方法扩展 Hash 或只是您的目标哈希对象

Or perhaps extend Hash or just your target hash object with a nested lookup method

module NestedHashLookup
  def nest *keys
    keys.reduce(self) {|m,k| m && m[k] }
  end
end

my_hash.extend(NestedHashLookup)
my_hash.nest 'key1', 'key2', 'key3'

哦,我们怎么能忘记 也许 单子?

Oh, and how could we forget the maybe monad?

Maybe.new(my_hash)['key1']['key2']['key3']

这篇关于Ruby - 访问多维哈希并避免访问 nil 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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