在 Ruby 中,我应该使用 ||= 还是如果已定义? 为了记忆?
我应该使用 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 宏,它透明地提供了这种行为。 是这样吗?
Should I use if defined?
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
Or ||=
@current_user_session ||= UserSession.find
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此外,更好的
||=
会生成有关未初始化实例变量的警告(至少在 1.8.6 和 1.8.7 上),而更详细的defineed?
版本则不会不是。另一方面,这可能会满足您的要求:
但这几乎肯定不会:
因为
@foo
将总是在此时定义。Additionally, the nicer
||=
produces a warning (on 1.8.6 and 1.8.7, at least) about uninitialized instance variables, while the more verbosedefined?
version does not.On the other hand, this probably does what you want:
But this almost certainly does not:
since
@foo
will always be defined at that point.Rails 确实有记忆功能,请查看下面的截屏视频以获取精彩的介绍:
http://railscasts.com/episodes /137-记忆化
Rails does have memoization, check out the screencast below for a great introduction:
http://railscasts.com/episodes/137-memoization
请注意:如果 x 返回 false,则 x ||= y 会指定 x = y。 这可能意味着 x 未定义、nil 或 false。
很多时候变量会被定义并且为 false,尽管可能不是在 @current_user_session 实例变量的上下文中。
如果您希望简洁,请尝试条件构造:
或 just:
如果您只需要初始化变量。
Be careful: x ||= y assigns x = y if x returns false. That may mean that x is undefined, nil, or false.
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:
or just:
if you just need to initialize the variable.