The random selection Ruby of the array sometimes returns the same value repeatedly

advertisements

I am using this to select a random Matchup, and I test it's results, and draw a random Matchup until it meets the criteria of a while loop:

m = Matchup.order("RANDOM()").first

The loop is set to break after 10 cycles (to avoid infinite loops), and I will arbitrarily break out of the loop, check the logs, and see that the Matchup is the same every time it went through the loop. A simplified version of the loop would be something like this:

counter = 0
while counter < 5
    m = Matchup.order("RANDOM()").first
    logger.debug('Matchup ID: ' + m.id)
    counter += 1
end

The log will look like this:

Matchup ID: 7
Matchup ID: 7
Matchup ID: 7
Matchup ID: 7
Matchup ID: 7

Why would m = Matchup.order("RANDOM()").first arbitrarily not pull a different Matchup? The strangest part is that sometimes it works without issue, and others it gets stuck in the loop b/c m is not changing. Any suggestions?

If you want to see the actual loop, you can see it here (in the getRandomMatchup function): https://github.com/jackerman09/wdis/blob/master/app/controllers/static_pages_controller.rb


To add another variant :)

ids = Matchup.pluck(:id)
m = Matchup.find( ids.shuffle.first )

This will work well unless the set of id values is excessive, in which case you are shuffling a very large array. However, in the 1k to 2k set size, it will not be noticeable to a user.

Or simply:

ids = Matchup.pluck(:id)
m = Matchup.find( ids.sample )

Will choose a random item from the ids array.