2011-09-17 55 views

回答

4

它说:

  1. ,除非当前没有设置(最新除非)
  2. 什么也不做,返回@current_user如果@current_user已经设置(在||=部分)
  3. 否则调用方法/帮手login_from_session并将结果分配给@current_user
  4. 否则如果上一次调用已返回nilfalse,调用方法/帮手login_from_cookie,结果在任何情况下,分配给@current_user
  5. 返回@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中只有nilfalse评估为布尔值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 

结合所有这些规则,你已经解释了方法。

相关问题