在Ruby中,我应该使用|| =还是定义? 记忆?
if defined?
我应该使用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是undefined,nil或false。
虽然可能不在@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
如果你只需要初始化变量。
Rails确实有memoization,请查看下面的截屏video,以获得精彩的介绍:
http://railscasts.com/episodes/137-memoization
class Product < ActiveRecord::Base extend ActiveSupport::Memoizable belongs_to :category def filesize(num = 1) # some expensive operation sleep 2 12345789 * num end memoize :filesize end
另外,更好的||=
会产生关于未初始化实例变量的警告(至少在1.8.6和1.8.7),而更详细的defined?
版本没有。
另一方面,这可能会做你想要的:
def initialize @foo = nil end def foo @foo ||= some_long_calculation_for_a_foo end
但这几乎肯定不会:
def initialize @foo = nil end def foo return @foo if defined?(@foo) @foo = some_long_calculation_for_a_foo end
因为@foo
将始终定义在那一点。