How to pick random element from array without repeating in Ruby?

…衆ロ難τιáo~ 提交于 2020-01-15 03:24:13

问题


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.



来源:https://stackoverflow.com/questions/51162191/how-to-pick-random-element-from-array-without-repeating-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!