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

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

    It's like lazy instantiation. If the variable is already defined it will take that value instead of creating the value again.

    0 讨论(0)
  • 2020-11-21 23:41

    This ruby-lang syntax. The correct answer is to check the ruby-lang documentation. All other explanations obfuscate.

    Google

    "ruby-lang docs Abbreviated Assignment".

    Ruby-lang docs

    https://docs.ruby-lang.org/en/2.4.0/syntax/assignment_rdoc.html#label-Abbreviated+Assignment

    0 讨论(0)
  • 2020-11-21 23:42
    Basically,


    x ||= y means

    if x has any value leave it alone and do not change the value, otherwise set x to y

    0 讨论(0)
  • 2020-11-21 23:43

    This is the default assignment notation

    for example: x ||= 1
    this will check to see if x is nil or not. If x is indeed nil it will then assign it that new value (1 in our example)

    more explicit:
    if x == nil
    x = 1
    end

    0 讨论(0)
  • 2020-11-21 23:45

    In short, a||=b means: If a is undefined, nil or false, assign b to a. Otherwise, keep a intact.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题