我正在玩创建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'
有没有办法确保至少调用一次question(),右()恰好一次和错误()n次或多次调用?
答案 0 :(得分:3)
不确定。只需添加一行
即可(@question_count ||= 0) += 1
显示question
方法的当前实现(对right
和wrong
类似),然后检查这些变量。
答案 1 :(得分: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