ruby - Ruby 中的“||=”运算符

标签 ruby

有人可以向我解释以下 Ruby 代码的含义吗? (我在一个人的项目中看到了这个代码片段):

car ||= (method_1 || method_2 || method_3 || method_4)

上面的代码和下面的代码有什么区别?

car = method_1 || method_2 || method_3 || method_4

------------更新----------------

好的,在阅读@Dave 的解释后,我明白了 ||= 运算符的含义,我的下一个问题是如果 method_2method_3method_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/

相关文章:

windows - 如何阻止 'gem' 实用程序访问我的主目录?

ruby-on-rails - Capistrano 部署超时

ruby-on-rails - 使用类常量作为 Ruby 哈希键

ruby - Ruby 中的祖先是什么,它们有什么用?

ruby - 使用 rspec 在 ruby​​ gem 测试中加载 fixture

ruby-on-rails - 将 Liquid 模板过滤器绑定(bind)到上下文

arrays - 如何比较特定索引处单独数组的元素?

ruby-on-rails - Ruby 从数组中随机选择有时会重复返回相同的值

ruby-on-rails - Ruby、gsub 和正则表达式

html - 我可以仅通过使用纯 CSS 来改变 Ruby 中文本区域的美观吗?