[英]Why the loop does not want to continue
The function asks a question, the answer to which should be YES or NO. function 提出一个问题,答案应该是“是”或“否”。 It takes the text of the question and returns the letter "y" or "n".
它接受问题的文本并返回字母“y”或“n”。 I have a Python code, I need to transform it to Ruby.
我有一个 Python 代码,我需要将其转换为 Ruby。
#Python code
def ask_yes_no(question):
response = None
while response not in ("y", "n"):
respone = input(question).lower()
return response
What did i do我做了什么
# 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. 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")
is a boolean operation on two strings; ("y" || "n")
是对两个字符串的 boolean 操作; since all strings are true in Ruby, the result is the first string.由于 Ruby 中的所有字符串都为真,因此结果是第一个字符串。 So therefore the result of the whole boolean operation is also true, so the
unless
is false, and the block is never entered.所以因此整个 boolean 操作的结果也是真的,所以
unless
是假的,并且永远不会进入块。
You can use include?
你可以使用
include?
to do the same as the Python version:与 Python 版本相同:
unless ["y", "n"].include?(response) || guessed_it
but the whole Ruby version can be translated much more directly:但是整个 Ruby 版本可以更直接地翻译:
def ask_yes_no(question)
puts question
response = nil
until ["y", "n"].include?(response) do
response = gets.downcase.strip
end
response
end
You could also use Ruby regex's.您也可以使用 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.