给我解释一行代码。RubyonRails
我在github上打开了一个“帮助者”页面,该页面位于github上的“改变的野兽”论坛,看到了以下代码:给我解释一行代码。RubyonRails,ruby,Ruby,我在github上打开了一个“帮助者”页面,该页面位于github上的“改变的野兽”论坛,看到了以下代码: def recent_topic_activity(topic) return false unless logged_in? return topic.last_updated_at > ((session[:topics] ||= {})[topic.id] || last_active) end 你能给我详细解释一下第三行吗 这是做什么用的 此构
def recent_topic_activity(topic)
return false unless logged_in?
return topic.last_updated_at > ((session[:topics] ||= {})[topic.id] || last_active)
end
你能给我详细解释一下第三行吗
- 这是做什么用的
- 此构造的工作原理:
我理解这句话的第一部分。如果(会话[:主题]| |={})[topic.id])
等于0,则为其分配一个空哈希。但我从未见过像这样的session[:topics]
()[topic.id]
topic.last_updated_at > something # this is a comparison therefore
# will return true or false
关于某物
:
(session[:topics] ||= {})[topic.id] || last_active # this is an OR (||)
# expression, it will return either the first part if it is not nil or false
# otherwise it will return the second part (last_active)
第一部分是:
让我们把第三行改写得不那么简洁
# 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][3]
存在,则您有session[:topics]
,否则为零。最后,您的问题包括()[topic.id]
。也许这是造成混乱的原因;再看一遍,这里没有我刚才说的主题(session[:topics]| |={})[topic.id]
topic_updated_at = (session[:topics] || {})[topic.id] || last_active