How to pick random element from array without repe

2019-07-14 15:16发布

问题:

I am new to coding and am trying to learn Ruby. I am working in a Rake. What should I use to ensure that the random selection never repeats the same response back to back?

array = ["1", "2", "3", "4", "5"]

task :array do 
  array = ["1", "2", "3", "4", "5"]
  ap(array.sample) 
end

回答1:

With array.shuffle.each{|x|} you can reorder the array, then traverse the new order, pulling items in a random order without repeating them.