lundi 31 janvier 2022

Getting wrong selection on an Array.sample Ruby

so I'm running into a problem where I'm trying to create a trivia game. I had a couple questions about it. Here is my current code.

  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

Whenever I run this Ruby code in my CMD or Command Line, it spits out a totally random answer rather than the answer I would like it to display.

Does anyone have a solution? Or better yet, would anyone be able to tell me how to use a hash/dictionary where the question is linked to the answer? Please help. :)




Aucun commentaire:

Enregistrer un commentaire