Selecting n random items from an array in ruby is quite simple
using the sort_by method provided by the Enumerable class. If we apply sort_by{ rand
}
to an array (or to a hash) we obtain the same array
randomly ordered. If we only want n random items from the array,
we can apply the slice method to the randomly orderer array to get
the first n elements. For example, suppose we want to get 3
random items from my_array:
> my_array = (1..10).to_a => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > my_array.sort_by{ rand }.slice(0..2) => [2, 9, 3]
You can find a more detailed explanation of how sort_by{
rand }
works in …