我正在研究無脂肪CRM的源代碼。我想了解的代碼在應用程序的一個助手,這個具體的行所做:瞭解紅寶石代碼行
options[:selected] = (@account && @account.id) || 0
看來選擇散列與關鍵:selected
值被設置爲實例變量的值@account
或0
(如果@account
不存在)。
&& @account.id
在做什麼?
我正在研究無脂肪CRM的源代碼。我想了解的代碼在應用程序的一個助手,這個具體的行所做:瞭解紅寶石代碼行
options[:selected] = (@account && @account.id) || 0
看來選擇散列與關鍵:selected
值被設置爲實例變量的值@account
或0
(如果@account
不存在)。
&& @account.id
在做什麼?
它確保@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
'andand'實際上是[gem](https://github.com/raganwald/andand/)雖然,對不對?從我所知道的情況來看,它並沒有被構建到Ruby中。 –
@JamesChevalier正確,這是一顆寶石。 –
它相當於寫作,
options[:selected] = (@account != nil ? (@account.id != nil ? @account.id : 0) : 0)
然而,Ruby程序員更喜歡你在你的問題中指出的方式,因爲你可以看到上面的代碼可能變得非常不可讀。另外,Ruby(以及其他動態編程語言,如JavaScript)具有真值和僞值的概念,允許編寫簡潔且更易讀的代碼。你可以閱讀這篇文章:A question of truth。
@DaveNewton謝謝戴夫,我修改了我的答案 –
既然是確保一個對象不是零一個非常普遍的問題,有一個在軌的方法(而不是在紅寶石直接):
options[:selected] = @account.try(:id) || 0
try(:id)
將返回nil
如果@account
是nil
或false
,在任何其他情況下將在@account
上調用:id
。這也意味着如果對象不是空或者不對ID做出響應,它會引發錯誤。
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。
在這裏看到的 - http://stackoverflow.com/questions/17461737/difference-between-and/17461794#17461794 –
看這裏 - HTTP ://stackoverflow.com/questions/995593/what-does-or-equals-mean-in-ruby –
之前做了一些研究,然後再問任何問題... –