Ruby:虽然循环意外破坏

时间:2017-01-21 16:16:10

标签: ruby while-loop

我是Ruby语言的初学者,我遇到了一个无法找到解决方案的问题。

我会放一大块代码,因为我不知道错误来自哪里...... 问题是,当我回答“完成?”这个问题的“是”或“否”时,程序会停止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!

1 个答案:

答案 0 :(得分: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的正确语法以及带有显式终止的正确循环。