什么|| =在Ruby中做

我一直在使用Ruby一段时间了,我一直看到这个:

foo ||= bar 

它是什么?

如果(且仅当) foonilfalse这将为foo指定bar

编辑:或者假,谢谢@mopoke。

运算符|| =是表达式的简写forms:

x = x || “默认”

运算符|| =可以是代码的简写:

x =“(某些后备值)”如果是x.nil?

来自: http : //en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

bar指定给foo除非foo是真值(不是falsenil )。

如果您将其用于实例变量,则可能需要避免使用它。 那是因为

 @foo ||= bar 

如果@foo之前未初始化,可以发出警告。 你可能想用

 @foo = bar unless defined?(@foo) 

要么

 @foo = bar unless (defined?(@foo) and @foo) 

取决于您是否只想检查@foo是否已初始化,或检查@foo是否具有真实性(即不是nilfalse )。