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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With