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

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

    irb(main):001:0> a = 1
    => 1
    irb(main):002:0> a ||= 2
    => 1
    

    Because a was already set to 1

    irb(main):003:0> a = nil
    => nil
    irb(main):004:0> a ||= 2
    => 2
    

    Because a was nil

提交回复
热议问题