In Ruby, there are two values that are considered logical false. The first is the boolean value false, theother is nil. Anything which is non-nil andnot explicitly false is true. Thefirst time though the method, @num is nil,which is treated as false and the logical orportion of ||= needs to be evaluated and ends upassigning the empty array to @num. Since that's now non-nil, itequates to true. Since true || x is true no matter what x is, in future invocations Ruby short circuits the evaluation and doesn't do the assignment.Ingeneral terms x ||= y is equivalent to x = x || y, it's just shorthand. It's implemented as the expandedform, same as &&=, +=or -=.Thepattern is best described as a "lazy initializer", that is thevariable is defined only once, but only when it's actually used. This is incontrast to an "eager initializer" that will do it as early aspossible, like inside the initialize method.You'llsee other versions of this pattern, like:def arr @num ||= begin stuff = [ ]
Comments
Leave a comment