應答的處理缺少在下面的代碼,但是你只有一個正確答案的控制
class Question
def initialize(text)
@text = text
@answers = []
@correct = nil #index of the correct answer inside @answers
end
def self.define(text, &block)
raise ArgumentError, "Block missing" unless block_given?
q = self.new(text)
q.instance_eval(&block)
q
end
def wrong(answer)
@answers << answer
end
def right(answer)
raise "Two right answers" if @correct
@answers << answer
@correct = @answers.size
end
def ask()
puts @text
@answers.each_with_index{|answer, i|
puts "\t%2i %s?" % [i+1,answer]
}
puts "correct is %i" % @correct
end
end
def question(text, &block)
raise ArgumentError, "Block missing" unless block_given?
Question.define(text, &block)
end
現在你可以用塊語法定義你的問題:
question('Who was the first president of the USA?') {
wrong 'Fred Flintstone'
wrong 'Martha Washington'
right 'George Washington'
wrong 'George Jetson'
}.ask
您可能也使用另一個定義的問題:
q = Question.new('Who was the first president of the USA?')
q.wrong 'Fred Flintstone'
q.wrong 'Martha Washington'
q.right 'George Washington'
q.wrong 'George Jetson'
q.ask
呃,我真的把答案放在'做'問題塊。 –
同意。在這種情況下,將正確答案設置爲單個值,而將錯誤添加到數組中。 – jer
「確定」這些名稱是什麼意思?如果他們不是,你想讓它出錯嗎? – jtbandes