本文介绍了如何从数组中选择随机元素而不在Ruby中重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

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

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


推荐答案

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

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中重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:24
查看更多