我试图在 Ruby 中获得简单的用户输入,但我无法让它工作。我正在使用 gets
方法,但程序从未停止要求我输入。我使用 Sublime Text 2 作为我的文本编辑器,我也在其中运行该程序(如果这有所不同)。
这是我的代码:
puts "What is your name?"
name = gets
puts "Hello " + name + ". How are you?"
这是给我的错误(和输出):
C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `+': can't convert nil into String (TypeError) from C:/Users/Sten Sootla/Desktop/Ruby workspace/exercise.rb:3:in `' What is your name? [Finished in 0.1s with exit code 1]
为什么程序不停止询问我的输入?
最佳答案
尝试使用 $stdin.gets
而不是简单的 gets
,这将强制输入来自标准输入
关于Ruby .gets 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17377864/