可借鉴的东西一个是
curr = curr.process
用替换来生成树,因为从来没做过面向对象法建树,所以比较新鲜
再一个就是UI类的运用
Code
class UI
def self.say(str)
print str + "\n"
end
def self.say_asking(str)
UI.say str =~ /[\?\.]$/ ? str : str + "?"
end
def self.ask_if(str)
UI.say_asking str
!((gets =~ /[Yy]/).nil?)
end
def self.ask(str)
UI.say_asking str
gets.chomp
end
end
class Animal
def initialize(name)
@name = name
end
def ask
UI.ask_if "Is it #{@name}"
end
def process
if ask
UI.say "I win. Pretty smart, aren' t I?"
self
else
UI.say "You win. Help me learn from my mistake before you go"
animal = UI.ask "What animal were you thinking of?"
question = UI.ask "Give me a question to distinguish #{animal} from #{@name}."
answer = UI.ask_if "For #{animal}, what is the answer to your question?"
UI.say "Thanks"
animal = Animal.new(animal)
Question.new(question,answer ? animal : self,!answer ? animal : self)
end
end
end
class Question
def initialize(question,yes,no)
@question = question
@yes = yes
@no = no
end
def ask
UI.ask_if @question
end
def process
if ask
@yes = @yes.process
else
@no = @no.process
end
self
end
end
curr = Animal.new("elephant")
loop do
curr = curr.process
break unless UI.ask_if("Play again?")
end