Best of Ruby Quiz 之四 Animal Quiz之我的答案

终于完全靠我自己的思考,做出来一个quiz,就是第四个Animal Quiz,代码贴一下,笔记稍后放出。
 1class AnimalQuiz
 2    @@animals = Array.new                                        # 用来保存问题和答案的数组,每个数组元素又是一个数组,
 3                                                                                    # [["cat", "Is it cute?", "y"], ["dog", "does it bark?","y"] ]
 4        
 5    def AnimalQuiz.add_animal(animal)            
 6      @@animals.push(animal)
 7    end
 8
 9    
10    def self.do_quiz
11        match_animal = ""
12        @@animals.each do |animal|
13            puts animal[1]                                            # 提问题
14            s = gets
15            if  s.chomp! == animal[2]                        # 答案是否与数组中给定的答案匹配
16                puts "is it " + animal[0+ "?"     # 匹配的情况,询问是否是当前数组元素中的动物
17                if get_yes_or_no=="y"                            # 读取输入,是当前数组元素中的动物
18                    match_animal = animal[0]                 # 取出动物
19                    break                                                        
20                end
21            else                                                                 # 答案不匹配,向下一个数组元素中的问题进发
22                next
23            end
24        end
25        if match_animal.empty?                                # 循环完毕,没有找到答案
26            puts "you win, what animal do u think of?"         # 向数组中累积问题
27            user_animal = Array.new
28            user_animal << gets.chomp!
29            puts "give me a question"
30            user_animal << gets.chomp!
31            puts "what is your answer to this question?(y or n)"
32            user_animal << gets.chomp!
33            add_animal(user_animal)
34            puts "thanks"
35        else
36            puts "i win,"                                                # 找到动物
37        end        
38    end
39
40    def self.go
41        puts "Think of an animal"
42        puts "is it an elephant?"                            # 对大象特殊处理
43        if get_yes_or_no != "y"                                # 不是大象,开始处理
44            do_quiz
45        end
46        while wanna_play_again? =="y"                    # 是大象,询问是否想继续
47            puts "Think of an animal"              # 继续,进行后续quiz
48            do_quiz
49        end
50    end
51
52    private
53        
54    def self.wanna_play_again?
55        puts "wanna play again?"
56        get_yes_or_no
57    end
58    
59    def self.get_yes_or_no                                    # 获取用户输入
60        s =gets         
61        while ((s=~/^\s*y\s*$/).nil? && (s=~/^\s*n\s*$/).nil? )
62            puts "please input 'y' or 'n'"
63             s = gets
64         end
65         s.chomp!
66    end
67    
68end
69
70AnimalQuiz.go
posted on 2007-07-24 11:15  小熊bryan  阅读(408)  评论(0编辑  收藏  举报