我正在通过编写一个简单的二十一点游戏来练习 Ruby。当用户被问到他们是想坚持还是扭曲时,我的程序似乎坚持他们选择了扭曲,即使他们明确触发了应该是中断的地方。我在这里抽象了问题:
choice = ""
loop do
print "Press any key to twist. Enter s to stick: "
choice = gets
break if choice == "s"
puts "twist"
end
print "stick"
知道是什么导致了一段非常简单的代码出现问题吗?无论我做什么,我都无法“坚持”打印。
最佳答案
当您调用 gets
时,您正在存储通过按 Return 而输入的输入以及 \n
换行符。避免这种情况的惯例是使用 gets.chomp
( String#chomp
) 从输入中去除空格。
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"
这在 User Input section at ruby-doc.org. 中得到解决
在 irb
控制台中,您可以通过简单地执行以下操作来测试它:
irb > input = gets
abcde
=> "abcde\n"
irb > input = gets.chomp
abcde
=> "abcde"
关于ruby - 为什么我没有成功摆脱这个 Ruby 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820721/