-
Notifications
You must be signed in to change notification settings - Fork 1
/
quest.rb
71 lines (60 loc) · 1.68 KB
/
quest.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env ruby
DATA_FILE = File.expand_path('../ruby.txt', __FILE__)
def parse_data(data)
data.split(/^=$/).map do |question_data|
parse_question(question_data)
end
end
def parse_question(question_data)
question_text, *answers_data = question_data.split(/^$/).map(&:strip).reject(&:empty?)
{ :question => question_text,
:answers => parse_answers(answers_data) }
end
def parse_answers(answers_data)
answers_data.map do |answer_data|
{ :answer => answer_data.sub(/^\* */,''),
:correct => answer_data.start_with?('*') }
end
end
def run
questions = parse_data(File.read(DATA_FILE))
while true
if questions.empty?
puts "Congratulation: no more questions to ask"
exit
end
question = questions.delete_at(rand(questions.size))
ask_question(question)
end
end
def ask_question(question)
puts "#{question[:question]}\n"
correct_choices = offer_answers(question)
while true
answer = gets
exit if answer.nil? || ["q", "quit"].include?(answer.chomp)
user_choices = answer.split(/[, ]/).map(&:strip)
if user_choices.sort == correct_choices.sort
puts "Congratulation"
puts "\n------------------------------------------------\n"
break
else
puts "We are sorry, try again"
end
end
end
def offer_answers(question)
answers = question[:answers].sort_by { rand }
choices = ('a'..'z').first(answers.size)
mapping = Hash[choices.zip(answers)]
choices.each do |choice|
answer = mapping[choice]
puts "#{choice}) #{answer[:answer]}"
puts
end
correct_choices = mapping.find_all { |_, answer| answer[:correct] }.map(&:first)
return correct_choices
end
if $0 == __FILE__
run
end