What does ||= (or-equals) mean in Ruby?

前端 未结 23 3322
情书的邮戳
情书的邮戳 2020-11-21 23:20

What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?

23条回答
  •  我在风中等你
    2020-11-21 23:26

    b = 5
    a ||= b
    

    This translates to:

    a = a || b
    

    which will be

    a = nil || 5
    

    so finally

    a = 5
    

    Now if you call this again:

    a ||= b
    a = a || b
    a = 5 || 5
    a = 5
    
    b = 6
    

    Now if you call this again:

    a ||= b
    a = a || b
    a = 5 || 6
    a = 5 
    

    If you observe, b value will not be assigned to a. a will still have 5.

    Its a Memoization Pattern that is being used in Ruby to speed up accessors.

    def users
      @users ||= User.all
    end
    

    This basically translates to:

    @users = @users || User.all
    

    So you will make a call to database for the first time you call this method.

    Future calls to this method will just return the value of @users instance variable.

提交回复
热议问题