簡體   English   中英

為什么循環不想繼續

[英]Why the loop does not want to continue

function 提出一個問題,答案應該是“是”或“否”。 它接受問題的文本並返回字母“y”或“n”。 我有一個 Python 代碼,我需要將其轉換為 Ruby。

#Python code 
def ask_yes_no(question):
    response = None
    while response not in ("y", "n"):
        respone = input(question).lower()
    return response

我做了什么

# Ruby code
def ask_yes_no(question)

    guessed_it = false
    response = ""

    puts question
    loop do

        unless (response == ("y" || "n"))  || guessed_it

            response = gets.downcase
            return response #&& guessed_it == true

        end

        break if guessed_it == true 
    end
end

ask_yes_no("
How is the weather?")

The logic of your Ruby code isn't the same as the Python version, and would be just as incorrect in Python as it is in Ruby.

("y" || "n")是對兩個字符串的 boolean 操作; 由於 Ruby 中的所有字符串都為真,因此結果是第一個字符串。 所以因此整個 boolean 操作的結果也是真的,所以unless是假的,並且永遠不會進入塊。

你可以使用include? 與 Python 版本相同:

unless ["y", "n"].include?(response) || guessed_it

但是整個 Ruby 版本可以更直接地翻譯:

def ask_yes_no(question)
    puts question
    response = nil
    until ["y", "n"].include?(response) do
        response = gets.downcase.strip
    end
    response
end

您也可以使用 Ruby 正則表達式。

def ask_yes_no(question)

    until (print question; gets.chomp.downcase =~ /y|n/) do
    end

    $~.to_s

end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM