如果我输入CTRL + D,是否可以打破ruby程序?

所以按照这个SO指导 ,我写了一个程序,如:

ruby_cli.rb

while true input = [(print 'Name: '), gets.rstrip][1] input.downcase.strip end 

我想要发生的是当我在命令提示符下按CTRL + D (我理解为EOF)时,ruby程序会跳出while循环并结束。 现在它命中input.downcase.strip行,我得到一个错误,例如nil的未定义方法`downcase’:NilClass(NoMethodError)

你会怎么做到这一点?

编辑:

我使用input = (print’Name:’),gets.rstrip的原因是因为我想在我要求的每个用户输入之前打印“Name”作为提示。

以下应该为您解决问题:

 loop do # infinite loop print 'Name: ' # prompt for input response = gets # get the response -- gets returns nil on EOF break unless response # break out of the loop unless the response is non-nil p response.rstrip.downcase # do whatever you want with the response end 

对于Unix / Mac,EOF是ctrl-d ,对于Windows,是ctrl-Z

尝试使用while循环检查gets ,如下所示:

 print 'Name: ' while line = gets # operate on line print 'Name: ' end