在Array.sample Ruby上选择错误



所以我在尝试创建一个琐事游戏时遇到了一个问题。我对此有几个问题。这是我当前的代码。

def random_question
#Going to work a way to use a hash instead of two seperate arrays
question_array = Array["Which state is known as the Evergreen State?", "What state is AZ?", "What state is CA?",
'What state is known as the Last Frontier?']
#random_question = question_array.shuffle.first
$ind = question_array.find_index($rand)
return $rand = question_array.sample
end
#If lives does not equal zero, let the game play out
while lives != 0
answer_array = Array["Washington", "Arizona", "California", "Alaska"]
puts random_question()
puts "!!!---" + $rand + "---!!!"
puts "What is your answer?"
#Takes answer(answer_response) and compares it to the correct answer
answer_response = gets.chomp
print answer_array[$ind.to_i - 1]
if answer_response == answer_array[$ind.to_i - 1]
puts "You're right!"
points += 10
puts "You have " + points.to_s + " points!"
else
puts "That is wrong. You lose a life!"
lives -= 1
puts "You have " + lives.to_s + " lives left!"
end

每当我在CMD或命令行中运行这个Ruby代码时,它都会抛出一个完全随机的答案,而不是我希望它显示的答案。

有人有解决方案吗?或者更好的是,有人能告诉我如何使用问题与答案相关的哈希/词典吗?请帮忙。:(

所以多亏了@rogerdpack的帮助,我昨晚找到了问题的答案。这是写出来的正确代码。:(

def random_question
#Going to work a way to use a hash instead of two seperate arrays
$question_array = Array["Which state is known as the Evergreen State?", "What state is AZ?", "What state is CA?",
'What state is known as the Last Frontier?']
$rand= $question_array.sample;
$ind = $question_array.find_index($rand);
return $rand
#random_question = question_array.shuffle.first
end
#If lives does not equal zero, let the game play out
while lives != 0
answer_array = Array["Washington", "Arizona", "California", "Alaska"]
puts "---------------------"
puts random_question()
puts "---------------------"
puts "What is your answer?"
puts "---------------------"
#Takes answer(answer_response) and compares it to the correct answer
answer_response = gets.chomp
if answer_response == answer_array[$ind]
puts "You're right!"
points += 10
puts "You have " + points.to_s + " points!"
else

因此,非常感谢所有帮助过我的人,但这段代码的运行方式是正确的,也是我想要的。

最新更新