访问嵌套哈希时如何避免 nil 元素的 NoMethodError? [英] How to avoid NoMethodError for nil elements when accessing nested hashes?

查看:17
本文介绍了访问嵌套哈希时如何避免 nil 元素的 NoMethodError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试访问不存在的哈希元素,我会收到 NoMethodError: undefined method '[]' for nil:NilClass.但是,我无法预测会出现哪些元素.

If I try to access a hash element that isn't present, I get NoMethodError: undefined method '[]' for nil:NilClass. However, I can't predict which elements will be present.

@param_info = {}
@param_info["drug"]["name"]
# => NoMethodError: undefined method `[]' for nil:NilClass

当元素意外 nil 时,如何避免引发此错误?

How can I avoid raising this error when an element is unexpectedly nil?

推荐答案

如果我正确理解了您的问题,即在缺少属性值的情况下让它变得宽容,那么您可以尝试以下操作:

If I understand your question correctly i.e. make it forgiving in case an attribute value is missing, then you could try the following:

@param_info.try(:fetch, :drug).try(:fetch, :name)

这也可能返回 nil,但这将消除错误 undefined methods '[]' for nil:NilClass

This might return nil as well, but this will get rid of the error undefined methods '[]' for nil:NilClass

更新:

为了处理不存在的键,您可以尝试以下操作.(从 Equivalent of try for a hash 得到这个提示):

In order to handle keys that do not exist, you could try the following. (Got this hint from Equivalent of try for a hash):

@param_info.try(:[], :drug).try(:[], :name)

这篇关于访问嵌套哈希时如何避免 nil 元素的 NoMethodError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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