2012-07-09 43 views
0

我發現我經常做這樣的事情在我的Ruby代碼:如何最小化嵌套的if語句? (紅寶石)

if person 
    if person.shirt 
    if person.shirt.sleeve 
    ... 
    end 
end 

..這怎麼做才能避免NoMethodErrors。我不知道是否有任何方式,我可以摺疊成一條線這一點,沒有明顯的

if person && person.shirt && person.shirt.sleeve 

基本上,我想使我的代碼更緊湊。

回答

4

這些如果你想用袖子做點什麼,對吧?

Rails有一個不錯的幫手,try。如果一切順利,它會返回值,否則返回nil。因此,在本例中,如果person.shirt甚至person本身爲零,那麼嘗試也會返回nil。

if sleeve = person.try(:shirt).try(:sleeve) 
    # do your stuff 
end 

對於香草紅寶石可以使用andand寶石提供類似的功能。

if sleeve = person.andand.shirt.andand.sleeve 
    # do your stuff 
end 
+0

謝謝。知道嘗試,不知道'andand'。 – varatis 2012-07-09 20:28:02