Problem with sort_by{rand}

Discussion in 'Ruby/Rails' started by ideaoforder, May 14, 2009.

  1. ideaoforder

    ideaoforder Active Member

    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?

  2. mistwang

    mistwang LiteSpeed Staff

    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.
  3. mistwang

    mistwang LiteSpeed Staff

    This problem has been confirmed in our lab. released ruby-lsapi 3.5 to reinitialize the random generator automatically.
  4. ideaoforder

    ideaoforder Active Member


    yup--the function is srand() in Ruby too. Worked like a charm. Thanks!
  5. mistwang

    mistwang LiteSpeed Staff

    if you upgrade to ruby-lsapi 3.5, you do not need to call srand()

Share This Page