||= 在 Ruby 中是什么意思? [英] What does ||= mean in Ruby?
问题描述
可能的重复:
在 Ruby 中 ||= 是什么意思?
||=
在 Ruby 中是什么意思?
What does ||=
mean in Ruby?
推荐答案
主要用作将变量初始化为某个值(如果尚未设置)的简写形式.
It's mainly used as a shortform for initializing a variable to a certain value, if it is not yet set.
将语句视为返回 x ||(x = y)
.如果 x
有一个值(除了 false
),只有 ||
的左边会被评估(因为 ||
short-circuts) 和 x
将不会被重新分配.但是,如果 x
是 false
或 nil
,则会评估右侧,这会将 x
设置为 y
和 y
将被返回(赋值语句的结果在右边).
Think about the statement as returning x || (x = y)
. If x
has a value (other than false
), only the left side of the ||
will be evalutated (since ||
short-circuts), and x
will be not be reassigned. However, if x
is false
or nil
, the right side will be evaluated, which will set x
to y
, and y
will be returned (the result of an assignment statement is the right-hand side).
参见 http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case 更多讨论.
这篇关于||= 在 Ruby 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!