2013-07-26 124 views
0

我正在研究無脂肪CRM的源代碼。我想了解的代碼在應用程序的一個助手,這個具體的行所做:瞭解紅寶石代碼行

options[:selected] = (@account && @account.id) || 0 

看來選擇散列與關鍵:selected值被設置爲實例變量的值@account0 (如果@account不存在)。

&& @account.id在做什麼?

+0

在這裏看到的 - http://stackoverflow.com/questions/17461737/difference-between-and/17461794#17461794 –

+0

看這裏 - HTTP ://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby –

+1

之前做了一些研究,然後再問任何問題... –

回答

7

它確保@account並非有錯,如果不是,它將選項設置爲帳戶的id。寫長手這將是相同的:

options[:selected] = if @account && @account.id 
         @account.id 
        else 
         0 
        end 

或者

options[:selected] = (@account && @account.id) ? @account.id : 0 

我可能會使用the andand gem這使得它看起來是這樣的:

options[:selected] = @account.andand.id || 0 
+0

'andand'實際上是[gem](https://github.com/raganwald/andand/)雖然,對不對?從我所知道的情況來看,它並沒有被構建到Ruby中。 –

+0

@JamesChevalier正確,這是一顆寶石。 –

0

它相當於寫作,

options[:selected] = (@account != nil ? (@account.id != nil ? @account.id : 0) : 0) 

然而,Ruby程序員更喜歡你在你的問題中指出的方式,因爲你可以看到上面的代碼可能變得非常不可讀。另外,Ruby(以及其他動態編程語言,如JavaScript)具有真值和僞值的概念,允許編寫簡潔且更易讀的代碼。你可以閱讀這篇文章:A question of truth

+0

@DaveNewton謝謝戴夫,我修改了我的答案 –

0

既然是確保一個對象不是零一個非常普遍的問題,有一個在軌的方法(而不是在紅寶石直接):

options[:selected] = @account.try(:id) || 0 

try(:id)將返回nil如果@accountnilfalse,在任何其他情況下將在@account上調用:id。這也意味着如果對象不是空或者不對ID做出響應,它會引發錯誤。

0
options[:selected] = (@account && @account.id) || 0 

這行代碼將不設置options[:selected]@account或0,而是@account.id或0的原因是(@account && @account.id)將返回評估的最後聲明,這將是@account.id如果雙方都是如此。

正如其他人所說,(@account && @account.id)將首先驗證@account實際存在;如果是的話,由於短路,它會檢查是否存在@account.id,如果有,將設置爲options[:selected]。但是,如果@account不存在,則該值將被設置爲0。