Ruby使用rand方法随机选择几个选项

时间:2015-05-14 10:49:20

标签: ruby

我的代码:

alea = ["x", " "]
num = alea.length
choice = rand(num)
veinte = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in veinte
    puts alea[choice]
end 

我希望我的代码随机选择几个选项,而不仅仅是一个。例如:

x

x
x

x
x
x

我该怎么做?

4 个答案:

答案 0 :(得分:1)

Array#sample是为此目的而发明的:

-encryptnativelibraries

答案 1 :(得分:0)

只需编辑代码:

alea = ["x", " "]
num = alea.length
choice = rand(num)
veinte = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
veinte.map { puts alea[rand(alea.length)] }

答案 2 :(得分:0)

根据您编写的代码,您获得的输出是正确的:

alea = ["x", " "]  # => Array on only two elements
num = alea.length  # => 2
choice = rand(num) # => rand(2) will only output either 0 or 1 which will always output either alea[0] or alea[1] which is " " or "x"

如果你真的想要一个Array的随机值,那么要么使用@mudasobwa建议的Array类的sample方法

答案 3 :(得分:0)

您似乎只需要一定数量的随机选择项目。在这种情况下,只需使用块形式的构造函数:

Array.new(10){ ["x", " "].sample }

#=>[" ", " ", "x", " ", "x", " ", "x", " ", "x", "x"]