Why am I not successfully breaking from this Ruby loop?

亡梦爱人 提交于 2019-12-12 14:04:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!