加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在访问嵌套哈希时为nil元素避免NoMethodEr

发布时间:2020-12-17 04:34:03 所属栏目:百科 来源:网络整理
导读:参见英文答案 Ruby Style: How to check whether a nested hash element exists14个 How to avoid NoMethodError for missing elements in nested hashes,without repeated nil checks?16个 如果我尝试访问不存在的哈希元素,我会得到NoM??ethodError:nil:N
参见英文答案 > Ruby Style: How to check whether a nested hash element exists14个
> How to avoid NoMethodError for missing elements in nested hashes,without repeated nil checks?16个
如果我尝试访问不存在的哈希元素,我会得到NoM??ethodError:nil:NilClass的未定义方法'[]’.但是,我无法预测哪些元素会出现.
@param_info = {}
@param_info["drug"]["name"]
# => NoMethodError: undefined method `[]' for nil:NilClass

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

解决方法

如果我正确理解您的问题,即在遗漏属性值的情况下使其宽容,那么您可以尝试以下方法:
@param_info.try(:fetch,:drug).try(:fetch,:name)

这也可能返回nil,但这将消除nil的错误未定义方法'[]’:NilClass

更新:

为了处理不存在的密钥,您可以尝试以下方法. (Got this hint from Equivalent of try for a hash):

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读