如何从数组中选择随机元素而不在Ruby中重复?(How to pick random element from array without repeating in Ruby?)

8 IT屋

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
解决方案

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

我是编码的新手,正在尝试学习Ruby。我在耙子里工作。
应该使用什么来确保随机选择永远不会重复出现相同的响应?



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



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

解决方案

使用 array.shuffle.each {| x |} ,您可以对数组重新排序,然后遍历新订单,以随机顺序提取商品,而无需重复。


本文地址:IT屋 » 如何从数组中选择随机元素而不在Ruby中重复?