ruby - @current_user ||= login_from_session 中 ||= 的用法 ?
迷茫
迷茫 2017-04-21 10:56:39
0
2
976

本想google, 但不知道这样的用法怎么去搜索,只能在这问了。
代码:

def current_user
    @current_user ||= login_from_session
  end
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(2)
PHPzhong
# 等价于
@current_user = @current_user || login_from_session

If this is written in multiple lines of code, it is indeed 空指针保护
But in your question, there is only this line in the whole method, this trick should be called Caching with Instance Variables, in order to improve the performance when calling this method multiple times

伊谢尔伦
@current_user ||= login_from_session
# 等价与
@current_user || @current_user = login_from_session
# 如果 @current_user 不为 nil 或 false,
# 就使 @current_user 值为 login_from_session 的返回值

This is a common approach among Ruby programmers: 空指针保护 .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template