【问题标题】:Getting wrong selection on an Array.sample Ruby在 Array.sample Ruby 上选择错误
【发布时间】:2022-02-01 03:43:09
【问题描述】:

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

  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 代码时,它会输出一个完全随机的答案,而不是我希望它显示的答案。

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

【问题讨论】:

  • 提示:你在分配之前使用$rand吗?
  • 我想我是,我注意到了。但我认为既然它是一个全局变量,它会起作用。抱歉,我对 Ruby 有点陌生。但我会调整它,看看是否有任何变化。 :)
  • 我继续做了@rogerdpack,它最终给我一个错误说明。 “states.rb:239:in gameplay': undefined method find_index' for nil:NilClass (NoMethodError) from states.rb:269:in `
    '”
  • 这里没有展示gameplay方法。
  • 如果在问题的开头说明了问答游戏的规则,读者会更容易理解你的代码。

标签: ruby random


【解决方案1】:

感谢@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

非常感谢所有提供帮助的人,但这段代码运行正常,并且符合我的意愿。

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多