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

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

    a ||= b
    

    is equivalent to

    a || a = b
    

    and not

    a = a || b
    

    because of the situation where you define a hash with a default (the hash will return the default for any undefined keys)

    a = Hash.new(true) #Which is: {}
    

    if you use:

    a[10] ||= 10 #same as a[10] || a[10] = 10
    

    a is still:

    {}
    

    but when you write it like so:

    a[10] = a[10] || 10
    

    a becomes:

    {10 => true}
    

    because you've assigned the value of itself at key 10, which defaults to true, so now the hash is defined for the key 10, rather than never performing the assignment in the first place.

提交回复
热议问题