What does ||= mean in Ruby? [duplicate]

It’s mainly used as a shortform for initializing a variable to a certain value, if it is not yet set.

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).

See http://dablog.rubypal.com/2008/3/25/a-short-circuit-edge-case for more discussion.

Leave a Comment