为什么我无法成功摆脱这个Ruby循环? [英] Why am I not successfully breaking from this Ruby loop?

查看:87
本文介绍了为什么我无法成功摆脱这个Ruby循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过编写一个简单的二十一点游戏来练习Ruby.当询问用户是否要粘住或扭曲时,我的程序似乎坚持要选择扭曲,即使他们明确触发了应该中断的情况.我已经在这里抽象了这个问题:

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.

推荐答案

调用gets时,将存储输入的输入以及\n换行符,方法是按 Return .避免这种情况的惯例是使用gets.chomp( String#chomp )从输入中去除空格.

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"

在ruby-doc.org的用户输入部分中解决了此问题.

This is addressed in the User Input section at ruby-doc.org.

irb控制台中,您可以通过简单地执行以下操作来对此进行测试:

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"  

这篇关于为什么我无法成功摆脱这个Ruby循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆