如何避免嵌套散列中缺少元素的 NoMethodError,而无需重复 nil 检查? [英] How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?

查看:23
本文介绍了如何避免嵌套散列中缺少元素的 NoMethodError,而无需重复 nil 检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种避免在深度嵌套散列中的每个级别检查 nil 的好方法.例如:

I'm looking for a good way to avoid checking for nil at each level in deeply nested hashes. For example:

name = params[:company][:owner][:name] if params[:company] && params[:company][:owner] && params[:company][:owner][:name]

这需要三项检查,并且会产生非常丑陋的代码.有什么办法可以解决这个问题?

This requires three checks, and makes for very ugly code. Any way to get around this?

推荐答案

Ruby 2.3.0 引入 HashArray 上的一个名为 dig 的新方法完全解决了这个问题.

Ruby 2.3.0 introduced a new method called dig on both Hash and Array that solves this problem entirely.

name = params.dig(:company, :owner, :name)

如果密钥在任何级别丢失,则返回 nil.

It returns nil if the key is missing at any level.

如果您使用的 Ruby 版本早于 2.3,您可以使用 ruby_dig gem 或自己实现:>

If you are using a version of Ruby older than 2.3, you can use the ruby_dig gem or implement it yourself:

module RubyDig
  def dig(key, *rest)
    if value = (self[key] rescue nil)
      if rest.empty?
        value
      elsif value.respond_to?(:dig)
        value.dig(*rest)
      end
    end
  end
end

if RUBY_VERSION < '2.3'
  Array.send(:include, RubyDig)
  Hash.send(:include, RubyDig)
end

这篇关于如何避免嵌套散列中缺少元素的 NoMethodError,而无需重复 nil 检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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