CLI Trivia

Iterators, arrays, hashes and allllll the variables

def self.random_question(question)puts "#{question.question}"
answers = []
answers << question.correct_answer
answers << question.incorrect_answers
randomized = answers.flatten.shuffle
q_a = {q: question, a: randomized}
randomized.each.with_index do |answer, i|
puts "#{i + 1}. #{answer}"
end
q_aend
def self.check_answer(q_a, input)
true if q_a[:q].correct_answer == input
end
def check_question
input = gets.strip.to_i - 1
answer = TriviaQuestion.check_answer(@q_a, @q_a[:a][input])
if answer && input.between?(0, 3)
puts "You got it!"

...

Pry is your best friend!!!

Pry was a pretty crucial part throughout the entire project, but the #check_question method is where it was absolutely essential. I used it to view variables and how the computer is interpreting what I’m inputting. For example, I needed to figure out the correct “input” argument to place in the #check_answer method. This needed to be the string of the correct answer in order for it to evaluate as true. Using pry, I was able to play with the @q_a hash. Seeing that @q_a[:a] returns the array of answers in the order the user is seeing it, I could align the users input with the array indices and use bracket notation to get the string value (@q_a[:a][input]).

Instance Variables

I learned a lot (more) about instance variables doing this project. My first approach was to avoid using them as much as possible, but this lead to a lot of loooong and messy methods in my CLI class. Using instance variables, I was able to break up my code. For example, I needed to save the users category selection in #get_category in order to display a corresponding question in #create_question.

@q = sorted_categories[input - 1]
@qs = TriviaQuestion.questions_in_category(@q.category)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store