Best of Ruby Quiz - Animal Quiz

可借鉴的东西一个是

ContractedBlock.gifcurr = curr.process

用替换来生成树,因为从来没做过面向对象法建树,所以比较新鲜

再一个就是UI类的运用

 

ContractedBlock.gif ExpandedBlockStart.gif 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

转载于:https://www.cnblogs.com/Tachikoma/archive/2008/07/31/1257197.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值