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

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

    As a common misconception, a ||= b is not equivalent to a = a || b, but it behaves like a || a = b.

    But here comes a tricky case. If a is not defined, a || a = 42 raises NameError, while a ||= 42 returns 42. So, they don't seem to be equivalent expressions.

提交回复
热议问题