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

To get a sample of 5 elements from an array with replacement in Ruby, you can use the sample method with an argument of the desired sample size, and rand() to generate the index of the sampled element:

main.rb
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sampled_array = Array.new(5) { array[rand(array.length)] }

puts sampled_array
120 chars
6 lines

This code will output 5 randomly sampled elements from the original array, with replacement. The Array.new method creates a new array of size 5 and fills it with elements sampled from the original array using rand() to generate a random index.

gistlibby LogSnag