Ruby’s array class has a method #sample() good for randomizing array output values.

[user_1, user_2, user_3, user_4].sample
#=> user_3
[user_1, user_2, user_3, user_4].sample
#=> user_1

It also takes a parameter of an integer. This works especially well when grabbing random data collections for sidebars or suggested reading.

# expensive call to get 10 or 20 records
[user_1, user_2, user_3, user_4, user_5 ...].sample(3)
#=> [user_5, user_3, user_1]

Now on the front end if a user selects a user we can remove it from the collection without hitting the api again filling the gap with a new user. Consider the Facebook suggested friend or ad sidebar sections.


Leave a Reply

Your email address will not be published. Required fields are marked *