get a sample of 5 elements from an array without replacement in ruby

You can use the .sample method in combination with the Array#length method to randomly select a sample of 5 unique elements from an array without replacement:

main.rb
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sampled_array = my_array.sample(5)
74 chars
3 lines

This will return a new array of 5 randomly chosen, non-repeating elements from the original array. If the original array has less than 5 elements, .sample will still return a shuffled version of the original array, but with no repeats. If the original array is empty, .sample will return an empty array.

gistlibby LogSnag