From: anler hp Date: 2010-01-18T08:32:39+09:00 Subject: Re: What does ||= represent in this situation? hello, the operator | | = is the same as the typical + =, -= and so on, why did exist in ruby and not in other languages is because in ruby any expression returns a value. here is an example very closed but pretty much less effective in other language a = false; a || a = c; this means, makes a = c only if a is falseš, same things happen with a ||= c -- equivalent to --> a = a || c (if a is false, the right side of the || will be evaluated and its value will be returned -this only happen in ruby-, so c is returned either true or false) sorry for my english > 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.