I am working in Ruby, and I am trying to test for a user's input (the variable kid
) being the same three times.
I want my method speak
to be called on endlessly until the user enters "BYE" three separate times when asked the three separate questions.
Right now, if the user inputs "BYE" even only for one question the entire conversation between the terminal and user ends.
Is there a way to have the program test for "BYE" being said three times, and only once said three separate times, have the conversation end?
kid = gets.chomp
unless kid == "BYE"
speak
end
I don't know if there is a really simple solution or only a complex one, but any answers help.
You need to keep track of how many times the user has input "BYE". When that number reaches 3 you exit:
byecount = 0
while kid = gets.chomp
case kid
when "BYE"
#increase the count of bye
byecount +=1
puts byecount
break if byecount == 3
else
#reset our count
byecount = 0
speak
end
end
The code resets to 0 on a non "BYE" answer.
I find a case
statement to be very handy in situations like this when dealing with different user input, especially coupled with regular expressions.
I suggest looking for a ruby tutorial about "loops" and "control flow".
I think the Ruby Primer lesson at rubymonk.com may have what you need.
This example may also be helpful:
times = 0 # keep track of iterations
while times < 10 # repeatedly, while this condition is true
puts "hello!" # output "hello!"
times += 1 # increase count of iterations
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.