新手问题 ||= 符号

xiaoronglv · August 29, 2012 · Last by xiaoronglv replied at August 29, 2012 · 2360 hits

http://railscasts.com/episodes/1-caching-with-instance-variables?view=asciicast

@current_user ||= User.find(session[:user_id])

@current_user || @current_user = User.find(session[:user_id])

以上两行代码是不是相同的效果?

||=这个符号是不是ruby定义的用法?

在 google 中无法搜索符号,大家碰到不明白的符号时,是如何搜索的。

😄

#1 楼 @ashchan

|| 是 or 的意思

如果@current_user为空,会执行后面的语句。效果类似:

unless @current_user
@current_user = User.find(session[:user_id])
end
You need to Sign in before reply, if you don't have an account, please Sign up first.