2011-06-26 61 views
1

我正在玩弄創建DSL。我使用http://jroller.com/rolsen/entry/building_a_dsl_in_ruby作爲指導。執行方法調用

鑑於這種DSL:

question 'Who was the first president of the USA?' 
wrong 'Fred Flintstone' 
wrong 'Martha Washington' 
right 'George Washington' 
wrong 'George Jetson' 

是有辦法,以確保問題()被調用至少一次,右()一次,以及錯誤的()N次或更多次?

+2

呃,我真的把答案放在'做'問題塊。 –

+0

同意。在這種情況下,將正確答案設置爲單個值,而將錯誤添加到數組中。 – jer

+0

「確定」這些名稱是什麼意思?如果他們不是,你想讓它出錯嗎? – jtbandes

回答

3

當然。只需添加一行

(@question_count ||= 0) += 1 

到無論你目前執行的question方法的樣子(以及類似的rightwrong),然後檢查這些變量。

0

應答的處理缺少在下面的代碼,但是你只有一個正確答案的控制

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