【问题标题】:What's the most effective way to check for nil in a nested hash在嵌套哈希中检查 nil 的最有效方法是什么
【发布时间】:2012-01-01 05:18:28
【问题描述】:

我有一个带有很多嵌套 Mash 的大型 Mash 对象。我想获得的一些数据是几层,例如:

phone = profile.phone_numbers.all.first.phone_number
title = profile.positions.all.first.title

但是,phone_numbers 或 position 可能为 nil 或为空。什么是 nil 检查最有效的方法,而不必检查每个级别。有没有通用的技术可以使用?

【问题讨论】:

  • 不,它实际上是一个 Mash。我提到它只是因为我的语法使用点运算符。 rubygems.org/gems/mash
  • 啊,不知道。酷。

标签: ruby


【解决方案1】:

Ickmaybe 可以为您提供帮助!

像这样使用它:

phone = maybe(profile) {|p| p.phone_numbers.all.first.phone_number}

# or like this. 
phone = profile.maybe.phone_numbers.
                maybe.all.
                maybe.first.
                maybe.phone_number

或者您可以选择更简单的解决方案:Object#andand。它的功能类似。

phone = profile.andand.phone_numbers.
                andand.all.
                andand.first.
                andand.phone_number

【讨论】:

  • maybe 和 andand 有区别吗?
  • 从你的角度来看,没有。它们以类似的方式发挥作用。在您发布此评论时更新了帖子。 :-)
【解决方案2】:

要知道的重要一点是,如果中间值为 nil,您希望发生什么。您希望分配的值是 nil 还是其他值?您希望处理继续还是停止或引发错误?

如果分配 nil 是可以接受的,您可以在该行添加 rescue nil 子句:

phone = profile.phone_numbers.all.first.phone_number rescue nil
title = profile.positions.all.first.title rescue nil

这将返回 nil,它将分配给变量,然后处理将继续。这样做有一些风险,因为如果干预方法或值为零,那么了解它可能对您有好处。 nil 值通常意味着在执行到该点之前没有正确分配某些东西,救援会掩盖这一点,使调试更加困难。

如果您想继续,但有机会在继续之前做出反应,请使用标准救援块:

begin
  phone = profile.phone_numbers.all.first.phone_number
rescue Exception => e
  STDERR.puts "Exception handled: #{ e }"
  phone = nil
end

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2013-12-06
    • 2013-07-06
    • 2019-04-10
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多