且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

||= 在 Ruby 中是什么意思?

更新时间:2023-01-24 13:20:49

主要用作将变量初始化为某个值(如果尚未设置)的简写形式.

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 将不会被重新分配.但是,如果 xfalsenil,则会评估右侧,这会将 x 设置为 yy 将被返回(赋值语句的结果在右边).

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 更多讨论.