Search code examples
rubyerbshufflesrand

Running Ruby as index.cgi, [1,3,5].shuffle always yield the same result


I do dump the value of RUBY_VERSION => 1.8.7

every time, the value of [1,3,5].shuffle is also [1,3,5] i have to add a srand(Time.now.to_i) or srand() in front of it to make it random... I thought srand is automatically called? but maybe not in a .cgi environment?

if i use irb, and look at [1,3,5].shuffle, and exit, and re-enter irb, each time the results are different.

by the way, ri shuffle didn't give anything, and the Array and Enumerable docs didn't list shuffle or shuffle! either... ?


Solution

  • Since I can't see how you checked to see whether it had changed or not, I can't say for sure, but I expect the issue has to deal with how you are checking whether it has changed or not. If you use shuffle, that does not alter the original array. So if you check the value of the original array rather than the returned result, it will appear that the method is returning the same value each time

    RUBY_VERSION    # => "1.8.7"
    
    a = [1,3,5]
    
    # a does not change, because shuffle does not mutate
    a.shuffle       # => [5, 1, 3]
    a               # => [1, 3, 5]
    
    # now a does change, because shuffle! does mutate
    a.shuffle!  # => [5, 3, 1]
    a           # => [5, 3, 1]
    

    Also, here are the docs http://ruby-doc.org/core-1.8.7/classes/Array.html#M000335