该函数提出一个问题,答案应该为是或否。它接受问题的文本并返回字母“ 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?")
答案 0 :(得分:2)
您的Ruby代码的逻辑与Python版本不同,在Python中与在Ruby中一样不正确。
("y" || "n")
是对两个字符串的布尔运算;由于在Ruby中所有字符串都是正确的,因此结果是第一个字符串。因此,整个布尔运算的结果也为true,因此unless
为false,并且永远不会输入该块。
您可以使用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
答案 1 :(得分:1)
您还可以使用Ruby正则表达式。
def ask_yes_no(question)
until (print question; gets.chomp.downcase =~ /y|n/) do
end
$~.to_s
end