From: John Merlino Date: 2010-01-18T22:44:18+09:00 Subject: Re: What does ||= represent in this situation? Josh Cheek wrote: > On Sun, Jan 17, 2010 at 11:31 AM, John Merlino > wrote: > >> n -= 1 >> > This code is (presumably) showing that it is expensive to calculate the > string "99 bottles of beer on the wall\n98 bottles ... \n no more > bottles of > beer" and so what it does instead is calculates the string the first > time > the method is called, but then not again after that. > > The first time the method is called, @expensive will be nil, which > evaluates > to false. So in the boolean expression, @expensive || "99 bottles ... " > , > the string will be returned. The ||= command can be thought of as > @expensive || ( @expensive = "99 bottles ... " ) > > In this case, if @expensive does not have a value, it will assign the > string > to it. After that, however, it will have the value, and so the string > will > not be assigned to it. This is useful, because the code that generates > the > string is expensive to perform, and so we will never perform it unless > we > know we need it, and after it has been performed, it should not have to > be > performed again. From my understanding, you're saying since @expensive is undefined the first time around, it is assigned the string "99 bottles". Since after that first time, it is defined, it won't return the string again. Now my question is if that's the case, what's the purpose of the while loop here where n will loop as long as it's greater than 0? -- Posted via http://www.ruby-forum.com/.