繁体   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