2012-01-04 51 views
1

我想用下面的代码重写下面的代码,但我被卡住了。ruby​​程序基本设计说明

def ask question 
good_answer = false 
while (not good_answer) 
    puts question 
    reply = gets.chomp.downcase 

    if (reply == 'yes' or reply =='no') 
     good_answer = true 
     if reply == 'yes' 
      answer = true 
     else 
      answer = false 
     end 
    else 
     puts 'Please answer "yes" or "no"' 
    end 
end 
answer 
end 

替换代码:

def ask question 
    puts question 
    reply = gets.chomp 
    if (reply == 'yes' or reply == 'no') 
     puts reply.capitalize 
    else 
     puts 'Please enter "yes" or "no"' 
     #jump the code to like 2 (but how?)- use while reply != empty & comment the below lines 
     puts question 
     reply = gets.chomp 
    end 
end 

我要跳转到程序的主要部分是没有任何跳转,跳转或我可以调用方法,该方法里面?

+0

Ruby通常是用两个空格缩进的,而不是四个。 – 2012-01-04 21:48:04

回答

-1
def ask question 
puts question 
reply = gets.chomp.downcase 
if (reply == 'yes' or reply == 'no') 
    puts reply.capitalize 
else 
    puts 'Please enter "yes" or "no"' 
    ask question # this does the looping of loop 
end 
end 

谢谢,对不起,我没有从我的剪贴板上一次复制它做好。

+0

做这个递归是完全没有必要的,你也改变了方法的语义。 – 2012-01-04 21:17:41

+0

Ed.S,这个东西的作品这是我想要的。但我并没有遵循你对他答案的评论。 – Clone 2012-01-04 21:35:42

+0

@克隆:好吧,没关系,但你只是在这里使用递归。当一个循环简单且更清晰时,您可能会冒险吹没有任何理由(不太可能在这里,但仍有可能)。 – 2012-01-04 21:45:46

2

我想跳转到程序的主要部分是否有任何转到,跳转或我可以调用该方法内的方法?

是的,它被称为循环,即您在原始代码中使用的是什么。为什么在这个世界上你想要用goto代替一个循环?没有意义。

然而它可以被简化。我不喜欢对“是”或“否”的检查,但我也没有时间重新调整程序。

def ask question 
    while true 
    puts(question) 
    reply = gets.chomp.downcase 
    if reply == 'yes' || reply == 'no' 
     return reply == 'yes' 
    else 
     puts('Please answer "yes" or "no"') 
    end 
    end 
end 
+0

谢谢,但我需要重新检查答案。有没有什么办法像我这样称呼'var.ask'。 – Clone 2012-01-04 20:53:12

+0

@克隆:我仍然不知道你在问什么。 – 2012-01-04 21:18:21

1

即使有goto声明,你也不应该使用它。这不仅是糟糕的形式,而且由于程序最终难以遵循,所以它会给维护人员带来各种麻烦。

一个更好的方法是定义适当的结构以您的问题和有效的答案,然后简单地遍历这些,收集结果到一个结构,你可以在以后使用:

# Auto-flush output buffer 
STDOUT.sync = true 

questions = [ 
    [ 'Is this a good question?', 'yes', 'no' ], 
    [ 'Is the sky blue?', 'yes', 'no' ], 
    [ 'Do hamsters fly?', 'no', 'yes' ] 
] 

answers_given = [ ] 

questions.each do |question, *answers| 
    print question + ' ' 

    while (true) 
    answer = gets 

    answer.chomp! 

    if (answers.include?(answer)) 
     puts "Thanks!" 

     answers_given << (answer == answers.first) 

     break 
    end 

    puts "You must answer one of #{answers.join(', ')}!" 
    print question + ' ' 
    end 
end 

questions.each_with_index do |(question, *answers), i| 
    puts "#{question} #{answers_given[i]}" 
end 
1

你可以试一下liek这样的:

def ask_question 
    puts('Please answer "yes" or "no"') until (reply = gets.chomp.downcase) =~ /^(yes|no)$/ 

    return reply == 'yes' 
end