From: Josh Cheek Date: 2010-01-18T04:06:12+09:00 Subject: Re: What does ||= represent in this situation? --001636b2b04b098ba7047d60ee85 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Jan 17, 2010 at 11:31 AM, John Merlino wrote: > Hey all, || is equal to Or. So what would ||= in this situation? > > def expensive > @expensive ||= > begin > n = 99 > buf = "" > begin > buf << "#{n} bottles of beer on the wall\n" > # ... > n -= 1 > end while n > 0 > buf << "no more bottles of beer" > end > end > > Thanks for all suggestions. Also if you can interpret this, that would > be nice. What it appears here is an attempt of a do while loop. > -- > Posted via http://www.ruby-forum.com/. > > 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. --001636b2b04b098ba7047d60ee85--