search

Home  >  Q&A  >  body text

ruby - @current_user ||= login_from_session 中 ||= 的用法 ?

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

def current_user
    @current_user ||= login_from_session
  end
迷茫迷茫2775 days ago978

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-21 10:58:39

    # 等价于
    @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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-21 10:58:39

    @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: 空指针保护 .

    reply
    0
  • Cancelreply