2012-01-03 94 views
2

我有這樣一個條件:紅寶石條件語句

if connection 
    if "name" == connection.name 
    ... 
    end 
end 

connection可能有nil值開始,所以我不能夠檢查if connection && "name" == connection.name

我怎樣纔能有效地簡化條件?

回答

2
unless connection.nil? || connection.name != "name" 
    #...Statements 
end 
+0

非常有意義簡明扼要! – 2012-01-03 07:06:45

8
if connection and connection.name == "name" 
    ... 
end 
+0

比上面的負面版本更容易閱讀和理解。 – Jasper 2012-01-03 08:04:35