2012-01-04 49 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