Heim  >  Fragen und Antworten  >  Hauptteil

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

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

def current_user
    @current_user ||= login_from_session
  end
迷茫迷茫2712 Tage vor917

Antworte allen(2)Ich werde antworten

  • PHPz

    PHPz2017-04-21 10:58:39

    # 等价于
    @current_user = @current_user || login_from_session

    如果这样写在多行代码中,确实是 空指针保护
    但在你的问题中,整个方法中只有这一行,这个技巧应该叫 Caching with Instance Variables,为了在多次调用这个方法时提高性能

    Antwort
    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 的返回值

    这是 Ruby 程序员的常用方法: 空指针保护

    Antwort
    0
  • StornierenAntwort