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

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

    a ||= b is a conditional assignment operator. It means if a is undefined or falsey, then evaluate b and set a to the result. Equivalently, if a is defined and evaluates to truthy, then b is not evaluated, and no assignment takes place. For example:

    a ||= nil # => nil
    a ||= 0 # => 0
    a ||= 2 # => 0
    
    foo = false # => false
    foo ||= true # => true
    foo ||= false # => true
    

    Confusingly, it looks similar to other assignment operators (such as +=), but behaves differently.

    • a += b translates to a = a + b
    • a ||= b roughly translates to a || a = b

    It is a near-shorthand for a || a = b. The difference is that, when a is undefined, a || a = b would raise NameError, whereas a ||= b sets a to b. This distinction is unimportant if a and b are both local variables, but is significant if either is a getter/setter method of a class.

    Further reading:

    • http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html

提交回复
热议问题