Problem with sort_by{rand}

#1
I'm running a RoR survey application that randomized question/answer order on a page using something like: answers.sort_by{rand}

This happens on several pages, each generating its own random number (in the view).

This sets the order on page render. It works fine on my local machine in both production and development mode running Mongrel, but doesn't work on my production server running Litespeed 4.0.3 (or 3.3 before that).

Strangely, when I restart the server, the value of rand appears to change. But it's the same for every page.

So it seems like this is some sort of caching problem where rand is only getting generated once.

Any ideas?

Thanks!
 

mistwang

LiteSpeed Staff
#2
I think it is the rand() function in Rails, the random generator has been initialized only once when the Rails Application starts, then RailsRunner for LSWS will fork() from the parent process, to process a request, then exit if idle for a while, then fork() another process when a new request comes in a while later. The random number generator has the same state for both children processes, so they produce the same random number.

The solution is to initialize the rondom number generator again before calling rand() function. In C it is srand() function, not sure what it is in Ruby.
 
Top