easylife 发表于 2013-2-4 20:05:03

Answer to Best of Ruby Quiz, quiz 4 "the animal quiz"

$answers = [[["an elephent", true]]]$stack = []def inputgets.chompend# convert_answer_to_questiondef c_a_t_q(key)"Is it a/an #{key}? (y or n)"enddef agent_answercase gets.chompwhen "y"    truewhen "n"    falseelse    raise "Invalid input, please input 'y' or 'n'"endenddef play_again?$stack.clearputs "Thanks.\nPlay again? (y or n)"if agent_answer    main_processelse    exitendend#convert_question_to_answerdef c_q_t_a(question)question.match(/Is it (.*)\?$/) ? $1 : raise("Invalid input, please input the sentance 'Is it xxx?'")end# warning def final_answer?$answers[$stack].size == ($stack + 1)enddef header_processputs "Think of an animal..."rand_num = rand($answers.size)    $stack << rand_num << 0end# push common stack to $stackdef p_c_s$answers << []($stack).times do |i|    $answers.last << $answers[$stack]endenddef body_processcurrent_pair = $answers[$stack][$stack]puts c_a_t_q(current_pair)if agent_answer == current_pair    if final_answer?      puts "I win. Pretty smart, aren't I?"    else      $stack += 1      body_process    endelse    puts "You win. Help me learn from my mistake before you go... \nWhat animal were you thinking of?"    real_answer = input    puts "Give me a question to distinguish #{real_answer} from #{current_pair}."    distinguish_question = c_q_t_a(input)    puts "For #{real_answer}, what is the answer to your question? (y or n)"    distinguish_answer = agent_answer    p_c_s    $answers.last << << endenddef main_processheader_processbody_processplay_again?rescue => eputs e.messageplay_again?endmain_process
页: [1]
查看完整版本: Answer to Best of Ruby Quiz, quiz 4 "the animal quiz"