The function asks a question, the answer to which should be YES or NO. It takes the text of the question and returns the letter "y" or "n". I have a Python code, I need to transform it to 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.
("y" || "n")
is a boolean operation on two strings; since all strings are true in Ruby, the result is the first string. So therefore the result of the whole boolean operation is also true, so the unless
is false, and the block is never entered.
You can use include?
to do the same as the Python version:
unless ["y", "n"].include?(response) || guessed_it
but the whole Ruby version can be translated much more directly:
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.
def ask_yes_no(question)
until (print question; gets.chomp.downcase =~ /y|n/) do
end
$~.to_s
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.