1
这种方法让人困惑 - 有人可以给我解释一下吗?红宝石 - 你能告诉我这里发生了什么吗
def current_user
@current_user ||= (login_from_session || login_from_cookie) unless @current_user == false
end
这种方法让人困惑 - 有人可以给我解释一下吗?红宝石 - 你能告诉我这里发生了什么吗
def current_user
@current_user ||= (login_from_session || login_from_cookie) unless @current_user == false
end
它说:
@current_user
如果@current_user
已经设置(在||=
部分)login_from_session
并将结果分配给@current_user
nil
或false
,调用方法/帮手login_from_cookie
,结果在任何情况下,分配给@current_user
@current_user
实例变量的值它可以被重写,这样
def current_user
if !(@current_user == false) # 1
if (@current_user)
return @current_user # 2
end
if (@current_user = login_from_session)
return @current_user # 3
end
if (@current_user = login_from_cookie)
return @current_user # 4
end
end
return @current_user # 5
end
更明确
这是ruby表现力的力量(和美)。请记住,在Ruby中只有nil
和false
评估为布尔值false在if/else语句和||
,&&
运营商
其他提示,以更好地理解,在Ruby中,你有以下规则:
任何函数的返回值对于函数最后计算的表达式,所以
def foo
any_value
end
是相同的
def foo
return any_value
end
的如果/除非在表达式的端语句是相同的,如果/除非声明,所以
do something if value
是相同的
if (value)
do_something
end
的||=
操作者是
@a ||= some_value
# is equivalent to
if [email protected]
@a = some_value
end
结合所有这些规则,你已经解释了方法。