我应该使用 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
宏,它透明地提供了这种行为。是这样吗?
最佳答案
注意:如果 x 返回 false,则 x ||= y 赋值 x = y。这可能意味着 x 未定义、为零或为假。
虽然可能不在 @current_user_session 实例变量的上下文中,但很多时候变量将被定义为 false。
如果你想要简洁,试试条件结构:
defined?(@current_user_session) ?
@current_user_session : @current_user_session = UserSession.find
或者只是:
defined?(@current_user_session) || @current_user_session = UserSession.find
如果您只需要初始化变量。
关于ruby-on-rails - 在 Ruby 中,我应该使用 ||= 还是如果已定义?内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963868/