我的代码:红宝石选择与兰特方法随机几个选项
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
我希望我的代码中随机选择几个选项Y没有唯一的一个。例如:
x
x
x
x
x
x
我该怎么做?
我的代码:红宝石选择与兰特方法随机几个选项
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
我希望我的代码中随机选择几个选项Y没有唯一的一个。例如:
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
#}
只需编辑代码:
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"
如果你真的想要一个数组的随机值,然后我们e @mudasobwa建议的Array类的示例方法
看起来您只需要一定数量的随机选择的项目。在这种情况下,只需使用块形式的Array构造函数:
Array.new(10){ ["x", " "].sample }
#=>[" ", " ", "x", " ", "x", " ", "x", " ", "x", "x"]
这更具可读性和优雅性。 – Bala
[1,2,3,4,5,6,7,8,9,10] .map do | elem | puts [“x”,“”] .sample end – Cleon
如果您只需要放置''x'-es或空格,'1.upto(10).each {puts [“x”,“”] .sample}更适用(甚至是“10.times {puts ...}”。)当你不需要结果时,你不应该“映射”。 “每个”都足够了。当你不需要它时,你可以忽略块变量。 – mudasobwa