如何在数组中生成新的随机单词元素



我正在尝试从数组元素中生成一个新的随机选择。目前,它会在第一次通过数组时随机选择,然后下一个选择是相同的,直到 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
colors = ["red", "green", "orange", "yellow", "blue", "purple"]   
correct_guesses = ["red","green","orange","yellow"]
total_guesses = 10
num_guess = 0
while num_guess < total_guesses do
  comp_guess = colors.sample
  puts comp_guess
  if(correct_guesses.include?(comp_guess))
    puts "You got it right."
    break
  else
    puts "You got it wrong. Guess again."
    num_guess = num_guess + 1
  end
  puts "The number of guess is " + num_guess.to_s
end

为正确答案创建一个外部循环

您可以通过在外部循环中迭代正确答案并使用 Array 方法(如 #shuffle! 和 #each_index)来处理随机化来执行所需的操作。当您想避免多次进行相同的猜测时,这通常比 #sample 更可取。例如:

colors  = %w[Red Green Orange Yellow Blue Purple]
answers = colors.shuffle.take 4
answers.each do |answer|
  puts "Secret color is: #{answer}"
  colors.shuffle!
  colors.each_index do |i|
    guess = colors[i]
    print "Guess #{i.succ}: "
    if guess == answer
      puts "#{guess} is right. "
      break
    else
      puts "#{guess} is wrong."
    end
  end
  puts
end

最新更新