【问题标题】:Is it possible to break out of a ruby program if I input CTRL+D?如果我输入 CTRL+D,是否可以跳出 ruby​​ 程序?
【发布时间】:2016-04-10 00:21:03
【问题描述】:

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

ruby_cli.rb

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

我想要发生的是,当我在命令提示符下按 CTRL+D(据我所知是 EOF)时,ruby 程序会跳出 while 循环并结束。现在它到达 input.downcase.strip 行,我收到一个错误,例如 undefined method `downcase' for nil:NilClass (NoMethodError)

你会如何做到这一点?

编辑:

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

【问题讨论】:

  • 这可能是因为在执行 downcast 行时,您没有检查是否在 EOF 中得到结果。
  • 请不要使用[(print 'Name: '), gets.rstrip][1]。这比简单地写在两行更难看也更慢。
  • @Vikyboss,我的印象是没有“EOF”字符这样的东西?
  • 您可以将其称为流的状态/条件。在您的情况下,流是标准输入。
  • Ruby 版本 2.1.0 documentation 表示 gets 将在 EOF 上返回 nil。但在您的情况下,rstrip 以某种方式在nil 上成功,只有下一行失败。我建议查找您的 ruby​​ 版本的文档。

标签: ruby


【解决方案1】:

以下内容应该可以为您解决问题:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 2022-01-18
      • 1970-01-01
      • 2016-10-22
      • 2018-04-22
      相关资源
      最近更新 更多