if !store.url.nil? and store.url != store.new_data.url
if ! store.url.nil? && store.url != store.new_data.url
OR
if (!store.url.nil? && store.url != store.new_data.url)
主要項目,我想對他諮詢:
是更好地把空間爆炸後?
& & - 或 - 和
|| - 或 - 或
if !store.url.nil? and store.url != store.new_data.url
if ! store.url.nil? && store.url != store.new_data.url
OR
if (!store.url.nil? && store.url != store.new_data.url)
主要項目,我想對他諮詢:
是更好地把空間爆炸後?
& & - 或 - 和
|| - 或 - 或
必須始終使用 「& &」 或 「||」在布爾語句中。
「和」以及「或」應該用於控制流,如if或unless。
如果你在Rails的工作,你也可以做
if store.url.present? && store.new_data.url != store.url
不要把空格否定感嘆號之後。在一般的ruby編碼慣例中使用括號不會被忽略,所以如果可以的話,請儘量避免。
http://avdi.org/devblog/2010/08/02/using-and-and-or-or-in-ruby/ –
這根本不是真的。 '和'通常比'&&'好,因爲它的優先級較低。 –
我會寫:
if store.url && store.url != store.new_data.url
(寫store.url.present?
如果一個空白的URL字符串被認爲是一個 「零」 值)
注意事項:
請勿使用nil?
,除非您明確地要區分nil
和false
(這是Ruby中唯一的錯誤值)。這些案例很少。
爆炸後沒有空格。
使用更通俗的&&
/||
超過and
/or
。
不要寫括號來表示完整的if/unless表達式,它們在Ruby中是不必要的(也不是慣用的)。
並參見http://phrogz.net/ProgrammingRuby/language.html#table_18.4 – chrispanda
不不不。 '&&'更高的優先級通常會在這樣的語句中需要更多*括號。 '和'在這裏是正確的選擇。 –
@Marnen:你是對的,在某些情況下,更高的優先級將需要更多的括號,編輯回答。然而,習慣用法是壓倒性的,人們使用&&,||。我的理解是,核心Ruby核心開發人員甚至拒絕包含和/或用於此用途的修補程序。 – tokland
我會怎麼做: if store.url and store.url != store.new_data.url
或者(如果你使用Rails或Ruby 1.9) if store.try(:url) != store.new_data.url
記住,nil
是紅寶石falsy。
@關閉選民:'&&不是''和'的同義詞,也不是''或''的同義詞,所以這不是一個「不建設性」的問題。 –
@Andrew。我不敢苟同。它們可能不是同義詞,但我認爲這是一個有效的疑問。它看起來更像是部分重複的:http://stackoverflow.com/questions/2083112/ruby-difference-between-and-or或 – tokland