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

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

    ||= is called a conditional assignment operator.

    It basically works as = but with the exception that if a variable has already been assigned it will do nothing.

    First example:

    x ||= 10
    

    Second example:

    x = 20
    x ||= 10
    

    In the first example x is now equal to 10. However, in the second example x is already defined as 20. So the conditional operator has no effect. x is still 20 after running x ||= 10.

提交回复
热议问题