doubt how to do this exercise [closed]

-1

I have an exercise in logic but I have not been able to understand how to do it

I have a txt file with the answer question format and a line break where it follows that same format:

1-question

answer

- jump line -

2-question

answer

- jump line -

etc ....

the idea is to read that txt file and show the question in the console and then the user can answer it if it is ok, continue with the next question if he does not show the question again.

I do not know if I made myself understood.

    
asked by Oscar Diaz 05.09.2017 в 00:12
source

1 answer

0

If the question file format always will be the same, you can do something like this:

questions = File.readlines('preguntas.txt')

questions.each_slice(3) do |question, answer, _|
  loop do
    puts question
    given_answer = gets.chomp

    break if  given_answer == answer.strip
  end
end
  • readlines reads the file and returns an array where each element is a line.
  • each_slice(3) iterates the array in blocks of 3, leaving the first line in the variable question , the second line in answer and the third one in _ (which we ignore as a blank line).
  • The loop always shows the same question until the user puts the correct answer.
answered by 05.09.2017 / 04:16
source