2012-01-01 50 views
2

我有一个很大的Mash对象有很多嵌套的Mashes。我想获得的一些数据是几层:什么是嵌套散列检查零的最有效的方法

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

但是,phone_numbers或职位可能是零或空。无需检查每个级别,最有效的零检查方式是什么?有一种通用的技术可以使用吗?

+0

不,它实际上是一个混搭。我只是提到它,因为我的语法使用了点运算符。 http://rubygems.org/gems/mash – James 2012-01-01 05:27:26

+0

啊,不知道。凉。 – 2012-01-01 05:32:54

回答

4

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 
+0

也许和andand有区别吗? – James 2012-01-01 05:28:02

+0

从你的角度来看,没有。它们的功能类似。在发布此评论时更新了帖子。 :-) – 2012-01-01 05:32:24

2

要知道的重要的事情是,如果中间值为零,你想要发生什么。你希望赋值为零还是另一个值?你想要处理继续还是停止或产生错误?

如果分配为零是可以接受的,你可以添加一个rescue nil子句行:

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

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

如果你想继续,但有机会继续前反应,使用标准的救援块:

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