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
|
# File 'lib/quiz.rb', line 15
def start(n=3)
nodes = XPath.match(@doc.root, '*[question]')
list = (0...nodes.length).to_a.sample(n)
questions = nodes.values_at(*list)
@results = questions.map do |q|
question, answer = q.text('question').strip, q.text('answer').strip
*options = XPath.match(q,'./options//option/text()').sort{rand}
a_options = options.length.times.map {|x| (97 + x).chr }.\
zip(options.map {|x| x.to_s.strip})
q_options = a_options.map {|x| " " * 2 + "%s) %s" % x}
answers = Hash[a_options.to_a]
if block_given? then
result = yield(question, q_options, answers, answer)
else
puts question + "\nis it ... \n" + q_options.join("\n")
student_answer = gets.chop; redo unless answers.keys.include? student_answer
result = answers[student_answer] == answer
reply = result ? '* correct *' : 'the answer was ' + answer
puts reply
end
result
end
end
|