问题
I am practising Ruby by writing a simple Blackjack game. When the user is asked whether they want to stick or twist, my program seems to insist they have chosen twist even if they explicitly trigger what should be the break. I have abstracted the problem here:
choice = ""
loop do
print "Press any key to twist. Enter s to stick: "
choice = gets
break if choice == "s"
puts "twist"
end
print "stick"
Any idea what is causing a problem in what should be a very simple piece of code? Whatever I do, I can't get 'stick' to print.
回答1:
When you call gets
you are storing the input entered along with the \n
newline character from pressing Return. The convention to avoid that is to use gets.chomp
(String#chomp) to strip whitespace from the input.
choice = ""
loop do
print "Press any key to twist. Enter s to stick: "
choice = gets.chomp
break if choice == "s"
puts "twist"
end
print "stick"
This is addressed in the User Input section at ruby-doc.org.
In an irb
console you can test this by simply doing something like:
irb > input = gets
abcde
=> "abcde\n"
irb > input = gets.chomp
abcde
=> "abcde"
来源:https://stackoverflow.com/questions/20820721/why-am-i-not-successfully-breaking-from-this-ruby-loop