在Ruby中,我应该使用|| =还是定义它?为了记忆? [英] In Ruby, should I use ||= or if defined? for memoization?
问题描述
我应该使用if defined?
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
或||=
@current_user_session ||= UserSession.find
我注意到if defined?
方法被越来越多地使用.一个相对于另一个有什么优势吗?就个人而言,我更喜欢||=
的可读性.我还认为Rails可能具有memoize
宏,该宏可以透明地提供此行为.是这样吗?
I noticed the if defined?
method being used more and more recently. Is there any advantage to one over the other? Personally, I prefer ||=
for readability. I also think Rails might have a memoize
macro which provides this behavior transparently. Is this the case?
推荐答案
注意:x || = y如果x返回false,则将x = y赋值.这可能意味着x是undefined,nil或false.
Be careful: x ||= y assigns x = y if x returns false. That may mean that x is undefined, nil, or false.
虽然在@current_user_session实例变量的上下文中可能并非如此,但变量会被多次定义和为假.
There are many times variables will be defined and false, though perhaps not in the context of the @current_user_session instance variable.
如果您希望简明扼要,请尝试使用条件构造:
If you desire conciseness, try the conditional construct:
defined?(@current_user_session) ?
@current_user_session : @current_user_session = UserSession.find
或者只是:
defined?(@current_user_session) || @current_user_session = UserSession.find
如果您只需要初始化变量.
if you just need to initialize the variable.
这篇关于在Ruby中,我应该使用|| =还是定义它?为了记忆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!