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

前端 未结 23 2753
情书的邮戳
情书的邮戳 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:45

    Suppose a = 2 and b = 3

    THEN, a ||= b will be resulted to a's value i.e. 2.

    As when a evaluates to some value not resulted to false or nil.. That's why it ll not evaluate b's value.

    Now Suppose a = nil and b = 3.

    Then a ||= b will be resulted to 3 i.e. b's value.

    As it first try to evaluates a's value which resulted to nil.. so it evaluated b's value.

    The best example used in ror app is :

    #To get currently logged in iser
    def current_user
      @current_user ||= User.find_by_id(session[:user_id])
    end
    
    # Make current_user available in templates as a helper
    helper_method :current_user
    

    Where, User.find_by_id(session[:user_id]) is fired if and only if @current_user is not initialized before.

提交回复
热议问题