问题描述
有人可以向我解释以下 Ruby 代码的含义吗?(我在一个人的项目中看到了这个代码片段):
Could some one explain to me the meaning of the following Ruby code? (I saw this code snippet in one guy's project):
car ||= (method_1 || method_2 || method_3 || method_4)
上面的代码和下面的代码有什么区别?
What is the difference between the above code and the following code?
car = method_1 || method_2 || method_3 || method_4
---------更新--------------
好的,在阅读@Dave 的解释后,我明白了 ||=
运算符的含义,我的下一个问题是如果 method_2
、method_3
和 method_4
返回一个值,哪个值会分配给car
?(我想 car
最初是 nil)
Ok, I got the meaning of ||=
operator after read @Dave's explanation, my next question is if both method_2
, method_3
and method_4
return a value, which one's value will be assigned to car
? (I suppose car
is nil initially)
推荐答案
这是'条件赋值'的赋值运算符
It's an assignment operator for 'Conditional Assignment'
见这里 -> http://en.wikibooks.org/wiki/Ruby_Programming/语法/运算符
条件分配:
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
运算符 ||= 是表达式的简写形式:
Operator ||= is a shorthand form of the expression:
x = x || "default"
看到OP的编辑后,这个例子只是这个的扩展,意思是:
After seeing OP's edit, the example is just an extension of this, meaning:
car = method_1 || method_2 || method_3 || method_4
会将method_1、method_2、method_3、method_4(按此顺序)的第一个非零或非假返回值分配给car
,否则将保留其旧值.
Will assign the first non-nil or non-false return value of method_1, method_2, method_3, method_4 (in that order) to car
or it'll retain its old value.
这篇关于'||=' Ruby 中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!