有人可以向我解释以下 Ruby 代码的含义吗? (我在一个人的项目中看到了这个代码片段):
car ||= (method_1 || method_2 || method_3 || method_4)
上面的代码和下面的代码有什么区别?
car = method_1 || method_2 || method_3 || method_4
------------更新----------------
好的,在阅读@Dave 的解释后,我明白了 ||=
运算符的含义,我的下一个问题是如果 method_2
,method_3
和method_4
返回一个值,哪个值会赋值给car
? (我想 car
最初是 nil)
最佳答案
它是“条件赋值”的赋值运算符
请看这里 -> http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators
条件赋值:
x = find_something() #=>nil
x ||= "default" #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "other" #=>"default" : value of x is not replaced if it already is other than nil or false
运算符 ||= 是表达式的简写形式:
x = x || "default"
编辑:
看到OP的编辑后,这个例子只是这个的扩展,意思是:
car = method_1 || method_2 || method_3 || method_4
将 method_1、method_2、method_3、method_4(按此顺序)的第一个非 nil 或非 false 返回值分配给 car
,否则它将保留其旧值。
关于ruby - Ruby 中的“||=”运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8506257/