2017-01-21 12 views
0

私はRuby言語の初心者です。私は解決策を見つけることができない問題に直面しています。Ruby:whileループが突然途切れする

私はエラーがどこから来るのかわからないので、私は大きなコードブロックを置くでしょう... 問題は、 "完了"という質問に "はい"または "いいえ"以外の何かに答えるときです。 "、プログラムはwhileループを停止し、次のコードブロックに進みます。それを止める代わりに、「はい」または「いいえ」を入れるまで、「はい」または「いいえ」を入れるようにもう一度尋ねる必要があります。

finished = "no" 
#create a hash in which the values are lists of values, so I can have keywords corresponding to authors, and lists of values corresponding to the lists of files created by each author 
hash = Hash.new do |hsh, key| 
    hsh[key] = [] 
end 

while finished == "no" 
    puts "What file would you like to implement?" 
    file = gets.chomp 
    time = Time.now 
    puts "Who's the author?" 
    author = gets.chomp 

    if hash[author].include? file 
     puts "There already is a file named \"#{file}\" corresponding to the author \"#{author}\"." 
    #gives a value to the value-list of a key 
    else hash[author].push(file) 
    end 

    puts "\nFinished? yes/no" 
    finished = gets.chomp 
    finished.downcase! 
    puts "" 

    #here, whenever i give the variable finished another value than "yes" or "no", it should ask again the user to put a value in the variable finished, until the value given is "yes" or "no" 
    case finished 
    when finished == "" 
     finished = gets.chomp 
     finished.downcase! 
    when finished != "yes" && finished != "no" && finished != "" 
     puts "Put \"yes\" or \"no\" please!" 
     finished = gets.chomp 
     finished.downcase! 
    end 

end 

TY:

は、ここに私のコードです!

答えて

2

正しいバージョンで表示するように容易になるだろう:

loop do # infinitely 
    # some logic I did not looked much into 

    # getting finished 
    finished = gets.chomp.downcase 

    case finished 
    when "" then break "Empty string" # ??? 
    when "yes" then break "yes" # return it from loop 
    when "no" then break "no" # return it from loop 
    else 
    puts "Put \"yes\" or \"no\" please!" 
    end 
end 

caseの正しい構文だけでなく、明示的に終了して適切なループに注意してください。

+0

答えをいただきありがとうございます。とにかく、Rubyコードに関するいくつかのことが分かりました。これは、私が必要としていたものが、既に持っているループの中のケースステートメントに対するループであることを理解していました。 少し検索しましたが、これが見つかりました http://stackoverflow.com/questions/22459495/looping-through-a-case-statement-in-ruby 結果:http://img11.hostingpics.net/ pics/189842rubycool.png 私のプログラムはうまくいきました。コードをもっと減らすことはできません。 – nounoursnoir