Class: Quiz

Inherits:
Object
  • Object
show all
Includes:
REXML
Defined in:
lib/quiz.rb

Instance Method Summary collapse

Constructor Details

#initialize(x) ⇒ Quiz

Returns a new instance of Quiz.



11
12
13
# File 'lib/quiz.rb', line 11

def initialize(x)
  @doc = Document.new(RXFHelper.read(x))
end

Instance Method Details

#scoreObject



44
45
46
47
48
49
# File 'lib/quiz.rb', line 44

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

end

#start(n = 3) ⇒ Object



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] # answers are in the hash, keys = a,b,c,d
    
    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