def current_user
@current_user ||= session[:user_id] && User.find(session[:user_id])
end
短短一行代碼,卻含有很多邏輯,以前老是搞混,這裏總結一下。
這句代碼相當於
def current_user
if @current_user
return @current_user
else
if session[:user_id]
@current_user = User.find(session[:user_id])
else
@current_user = nil
end
return @current_user
end
end
展開後的代碼看起來很噁心,代碼意思爲:如果@current_user不爲空直接返回@current_user。
如果@current_user爲空,則根據session中的user_id判斷是否登錄,如果已經登錄則查找出用戶信息並返回。如果沒有登錄則返回空。
這裏總結下各符號用法:
and 與 && 爲和,區別是and優先級比&&低。
or 與 || 爲或,not與!爲非,區別均是前者優先級低於後者
&&=, !=, ||=這個比較靈活,以前習慣用Java,可以認爲它相當於Java裏的+=,-=。
a &&= b即爲a = a && b。可見Ruby比Java靈活很多。
Ruby的&&, ||與其它語言有些不同。
&&運算法則爲:左邊爲false或nil時,直接分別返回false或nil,右邊將不會運算。
左邊不爲false或nil時,返回右邊的對象。
||運算法則爲:左邊爲false或nil時,返回右邊的對象。
左邊不爲false或nil時,直接返回左邊的對象,右邊的不會運算。
我整理了幾個例子:
puts false && "abc" # => false
puts nil && "abc" # => nil
puts true && "abc" # => "abc"
puts "123" && "abc" # => "abc"
puts false || "abc" # => "abc"
puts nil || "abc" # => "abc"
puts true || "abc" # => true
puts "123" || "abc" # => "123"
===============如果你想深入請看下面,不深入就算了===============
其實||=這個運算符裏面比較複雜,或者說有點亂。
x ||= y
#相當於
x || x=y
#而不是
x = x||y
#區別在於如果x存在且不爲空時不會執行任何操作,直接返回。
#還相當於
if defined? x
x || x=y
else
x = y
end