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



我的代码:

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

我该怎么做?

Array#sample就是为了这个目的而发明的:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map do |elem| 
  [elem, [true, false].sample]
end.to_h
#⇒ {
#   1 => true,
#  10 => false,
#   2 => true,
#   3 => true,
#   4 => false,
#   5 => true,
#   6 => false,
#   7 => true,
#   8 => false,
#   9 => false
#}

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

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

编辑你的代码:

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)] }

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

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"

如果你真的想从数组中获得一个随机值,那么使用@mudasobwa

所建议的数组类的示例方法。

最新更新