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

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

    Concise and complete answer

    a ||= b
    

    evaluates the same way as each of the following lines

    a || a = b
    a ? a : a = b
    if a then a else a = b end
    

    -

    On the other hand,

    a = a || b
    

    evaluates the same way as each of the following lines

    a = a ? a : b
    if a then a = a else a = b end
    

    -

    Edit: As AJedi32 pointed out in the comments, this only holds true if: 1. a is a defined variable. 2. Evaluating a one time and two times does not result in a difference in program or system state.

提交回复
热议问题