From: John Merlino Date: 2010-01-18T02:58:05+09:00 Subject: Re: What does ||= represent in this situation? John Merlino wrote: > 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. > > I can't figure out how to edit a post. But I don't need anyone to > interpret the code from "begin" to "end". I know this is executing n > until it is no longer greater than 0. But what I'm trying to find is > something similar to what can be done in javascript: > > In javascript, there are cases where you have a variable called, let's > say, old which contains 50 positions in an array. Now you want each > position of the array to be unique. But at the same time, you want to > generate random numbers for each item of the array: > > var old = new array(20) > var new > do { > new = Math.floor(Math.random()*100) + 1; > } > while (old[new]); > > old[new] = true; > > Is there a way to do a do while loop like this in Ruby? Something like this? def unique_num @unique_num ||= begin old = [75] #The old variable holds 75 indexes of an array. new = math.floor(math.random) * 100 + 1 #The new variable yields a random number from 1 to 100. begin old << new #We append the random number into the array. end while old[new] #We loop again if the number already exists, until we get another number in the position. old[new] = true #We set it to true since the number is now in the array. end -- Posted via http://www.ruby-forum.com/.