什么时候使用"|| =" Rails中的运算符?它的意义是什么? [英] When do we use the "||=" operator in Rails ? What is its significance?
问题描述
可能重复:
操作符|| =在红宝石中代表什么?
Possible Duplicate:
What does the operator ||= stands for in ruby?
我对Rails中||=
运算符的用法感到困惑.我无法在网络上找到任何有用的信息.谁能指导我?
I am confused with the usage of ||=
operator in Rails. I couldn't locate anything useful on the web. Can anyone please guide me?
请让我知道您是否知道任何网络链接.
Do let me know if there are any weblinks that you are aware of.
我想要以下声明的意思:
I would like what the following statement means:
@_current_user ||= session[:current_user_id] &&
User.find(session[:current_user_id])
推荐答案
让我们分解一下:
@_current_user ||= {SOMETHING}
这就是说,如果@_current_user
为nil
,false
或未定义,则将其设置为{SOMETHING}
.否则,将其设置为@_current_user
,或者什么也不做.扩展形式:
This is saying, set @_current_user
to {SOMETHING}
if it is nil
, false
, or undefined. Otherwise set it to @_current_user
, or in other words, do nothing. An expanded form:
@_current_user || @_current_user = {SOMETHING}
好,现在到右侧.
session[:current_user_id] &&
User.find(session[:current_user_id])
您通常会看到&&
仅带有布尔值,但是在Ruby中,您不必这样做.这里的技巧是,如果session[:current_user_id]
不是nil,并且User.find(session[:current_user_id])
不是nil,则表达式的计算结果为User.find(session[:current_user_id])
,否则为nil.
You usually see &&
with boolean only values, however in Ruby you don't have to do that. The trick here is that if session[:current_user_id]
is not nil, and User.find(session[:current_user_id])
is not nil, the expression will evaluate to User.find(session[:current_user_id])
otherwise nil.
所以用伪代码将它们放在一起:
So putting it all together in pseudo code:
if defined? @_current_user && @_current_user
@_current_user = @_current_user
else
if session[:current_user_id] && User.find(session[:current_user_id])
@_current_user = User.find(session[:current_user_id])
else
@_current_user = nil
end
end
这篇关于什么时候使用"|| =" Rails中的运算符?它的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!