Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not successfully breaking from this Ruby loop?

Tags:

loops

ruby

break

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.

like image 323
Chris Butcher Avatar asked Jul 12 '26 08:07

Chris Butcher


1 Answers

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"  
like image 92
Michael Berkowski Avatar answered Jul 15 '26 05:07

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!