get a sample of 5 elements from an array in ruby

To get a sample of 5 elements from an array in Ruby, you can use the Array#sample method. The sample method returns a random element (or elements) from the array.

To get a sample of 5 elements, you can pass the number 5 as an argument to the sample method:

main.rb
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_sample = my_array.sample(5)
puts my_sample.inspect
97 chars
4 lines

This will output something like:

main.rb
[2, 5, 9, 7, 1]
16 chars
2 lines

Note that the sample method does not modify the original array, it just returns a new array with the sampled elements.

gistlibby LogSnag