讓重寫3號線要少簡潔。
# set topics hash to load from the session.
# If nothing in session, use an empty hash
topics_hash = session[:topics] || {}
# Look in the topics hash for a specific topic id.
# if nothing is found, use last_active (whatever that is)
topic_updated_at = topics_hash[topic.id] || last_active
# If the topics last_updated_at timestamp is greater than (meaning later in time)
# than the topic_updated_at we calculated above, return true. Otherwise false.
return topic.last_updated_at > topic_updated_at
括號中的數值是第一評估,然後像一個單一的值進行處理。這意味着上述代碼中的任何地方都有一個變量名稱,您可以用將該變量設置爲括號的代碼替換它。所以,這兩條線:
topics_hash = session[:topics] || {}
topic_updated_at = topics_hash[topic.id] || last_active
可能成爲一條線,做同樣的事情:
topic_updated_at = (session[:topics] || {})[topic.id] || last_active
你可以在理論上做那種編碼爲一個完整的程序,最大限度地提高複雜性的每一行。有些人喜歡它。在實踐中,它使得很難理解正在發生的事情。
所以第三行簡單地將所有這些步驟巧妙地壓縮到單個表達式中。也許太聰明瞭。
'>'比較兩次:是第一次後。如果'topic.id'是3,那麼說,如果'session [:topics]'存在,你有'session [:topics] [3]',否則爲零。最後,你的問題包括'()[topic.id]'。也許這是造成混亂;再看一遍,沒有'()'。 – Matt
()[topic.id]我在說這個(session [:topics] || = {})[topic.id] – kirqe