【发布时间】:2014-11-18 21:41:01
【问题描述】:
我正在尝试从数组元素中生成一个新的随机选择。目前,它在第一次通过数组时随机选择,然后下一次选择相同,直到 10 次。
colors = ["red", "green", "orange", "yellow", "blue", "purple"]
comp_guess = colors.sample
correct_guesses = ["red","green","orange","yellow"]
total_guesses = 10
num_guess = 0
while num_guess < total_guesses do
if(correct_guesses.include?(comp_guess))
puts comp_guess
puts "You got it right."
num_guess = num_guess + 1
else
puts "You got it wrong. Guess again."
end
puts "The number of guess is " + num_guess.to_s
end
运行后的输出。一旦它通过循环,我想要新的随机数。
orange
You got it right.
The number of guess is 1
orange
You got it right.
The number of guess is 2
orange
You got it right.
The number of guess is 3
orange
You got it right.
The number of guess is 4
orange
You got it right.
The number of guess is 5
orange
You got it right.
The number of guess is 6
orange
You got it right.
The number of guess is 7
orange
You got it right.
The number of guess is 8
orange
You got it right.
The number of guess is 9
orange
You got it right.
The number of guess is 10
【问题讨论】:
-
你的意思是一个新的随机颜色?只需移动循环内选择随机颜色的线即可。
-
每次在循环内采样,例如
correct_guesses.include?(colors.sample)