“||="是什么意思?操作数代表红宝石 [英] What does the "||=" operand stand for in ruby
本文介绍了“||="是什么意思?操作数代表红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在 Ruby 中 ||= 是什么意思?
我是这样测试的:
>> a||=3
=> 3
>> a
=> 3
>> a||=b
=> 3
>> b
NameError: undefined local variable or method `b' for main:Object
from (irb):11
推荐答案
它是逻辑 OR 运算的简写.相当于:
It is the shorthand for a logical OR operation. It is equivalent to:
a || a = b
注意:上述代码示例已更正,以反映扩展 a ||= b
时的真实(如果不直观)行为.感谢为我指出这一点的人.这里是来源
Note: The above code sample has been corrected to reflect the true (if unintuitive) behavior if expanding a ||= b
. Thanks to the people who pointed that out for me. Here is the source
如果 a
的计算结果为真,它将保持原样,否则 b
将分配给 a
.在 ruby 中,nil
的计算结果为 false
,因此您可以看到这对于延迟加载和默认值分配有何用处.
if a
evaluates to true it will remain as is, otherwise b
will be assigned to a
. In ruby nil
evaluates to false
, so you can see how this is useful for lazy loading and default value assignment.
这篇关于“||="是什么意思?操作数代表红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文