向我解释一行代码。 Ruby on Rails

时间:2014-01-22 19:26:34

标签: ruby

我在github上打开了 changed_beast 论坛的帮助页面之一,看到了这段代码:

  def recent_topic_activity(topic)
    return false unless logged_in?
    return topic.last_updated_at > ((session[:topics] ||= {})[topic.id] || last_active)
  end 

你能详细解释我的第3行吗?

  • 这是">" for。
  • 的内容
  • 这种结构如何运作:(session[:topics] ||= {})[topic.id])

    我理解该行的第一部分。如果session[:topics]等于0,则空哈希分配给它。但我从来没有见过这样的()[topic.id]

这是该页面:git

提前致谢。 我是铁杆上的红宝石,但不是一个总的菜鸟。

2 个答案:

答案 0 :(得分:4)

让我们重写那条第三行不那么简洁。

# 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

理论上,你可以对整个程序进行那种编码,最大限度地提高每一行的复杂性。有些人喜欢它。在实践中,它很难理解发生了什么。

所以第3行只是巧妙地将所有这些步骤压缩成单个表达式。也许太聪明了。

答案 1 :(得分:3)

让我们分解一下:

topic.last_updated_at > something # this is a comparison therefore
# will return true or false

关于something

(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)

第一部分是:

(session[:topics] ||= {})[topic.id] # this is accessing a nested hash
# (session is a hash), with the key `topic.id`
#
# if session[:topics] exist, it must be a hash so this is like saying:
#   session[:topics][topic.id]
#
# if session[:topics] is nil, then it will be assigned an empty hash
# which will be accessed