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

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

    If X does NOT have a value, it will be assigned the value of Y. Else, it will preserve it's original value, 5 in this example:

    irb(main):020:0> x = 5
    => 5
    irb(main):021:0> y = 10
    => 10
    irb(main):022:0> x ||= y
    => 5
    
    # Now set x to nil. 
    
    irb(main):025:0> x = nil
    => nil
    irb(main):026:0> x ||= y
    => 10
    

提交回复
热议问题