Write a quiz in Ruby

This code will read a file called quiz.xml, ask the user 3 questions and then give them a score. You are free to do what you like with this code, just bare in mind it only works in Ruby 1.9 or above.

#!/usr/bin/ruby

# file: quiz.rb

require 'rexml/document'
include REXML

doc = Document.new(File.open('quiz.xml','r').read)

nodes = XPath.match(doc.root, 'q')
n = 3; max = nodes.length
list = n.times.inject([]) {|r,n| v = rand(max) while v.nil? or r.include? v; r << v}

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 = %w(a b c d).zip(options.map {|x| x.to_s.strip})
  q_options = a_options.map {|x| " " * 2 + "%s) %s" % x}
  h = Hash[a_options.to_a] # answers are in the hash, keys = a,b,c,d
  puts question  "\nis it ... \n" + q_options.join("\n")
  
  student_answer = gets.chop; redo unless h.keys.include? student_answer
  
  result = h[student_answer] == answer
  reply = result ? '* correct *' : 'the answer was ' + answer
  puts reply
  result
end

tally = (results - [false]).size
percent = 100 / (results.size / tally.to_f)
your_score = "you scored %s%" % percent.to_i

puts your_score


output:

What city is the capital 
of Scotland?
is it ...
  a) Oban
  b) Aberdeen
  c) Edinburgh
  d) Glasgow
c
* correct *

Who is the first minister of Scotland?
is it ... 
  a) Kenny MacAskell
  b) Alex Salmond
  c) Henry McLeish
  d) Simon Dunsmore
a
the answer was Alex Salmond

Who invented the televsion?
is it ... 
  a) Alexander Graham Bell
  b) John Logie Baird
  c) Philo Taylor Farnsworth
  d) Thomas Edison
b
* correct *

you scored 66%

input file: quiz.xml


  

<question>  What city is the capital of scotland?         </question>
<options>
  <option>  Edinburgh  </option>
  <option>  Glasgow    </option>
  <option>  Aberdeen   </option>
  <option>  Oban       </option>
</options>
<answer>    Edinburgh  </answer>
<question>  Who is the first minister of Scotland?   </question>
<options>
  <option>  Henry McLeish    </option>
  <option>  Simon Dunsmore   </option>
  <option>  Alex Salmond     </option>
  <option>  Kenny MacAskell  </option>
</options>
<answer>    Alex Salmond     </answer>
<question>  Who is the Cabinet Secretary for Justice in Scotland?   </question>
<options>
  <option>  Henry McLeish    </option>
  <option>  Simon Dunsmore   </option>
  <option>  Alex Salmond     </option>
  <option>  Kenny MacAskell  </option>
</options>
<answer>    Kenny MacAskell  </answer>
<question>  Who invented the televsion?   </question>
<options>
  <option>  Philo Taylor Farnsworth   </option>
  <option>  Thomas Edison             </option>
  <option>  John Logie Baird          </option>
  <option>  Alexander Graham Bell     </option>
</options>
<answer>    John Logie Baird  </answer>
Tags:
Source:
0900hrs.txt
Published:
08-02-2012 09:00