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.


# 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

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

puts your_score


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

Who is the first minister of Scotland?
is it ... 
  a) Kenny MacAskell
  b) Alex Salmond
  c) Henry McLeish
  d) Simon Dunsmore
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
* correct *

you scored 66%

input file: quiz.xml


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