如何在访问嵌套散列时避免使用nil元素的NoMethodError? [英] How to avoid NoMethodError for nil elements when accessing nested hashes?

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

问题描述

如果我尝试访问不存在的哈希元素,我得到 NoMethodError:undefined方法'[]'为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 ,但是这将消除错误未定义方法'[]'为nil:NilClass

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

更新:

为了处理不存在的密钥,您可以尝试以下操作。 (从等效的尝试中得到这个提示):

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天全站免登陆