代码之家  ›  专栏  ›  技术社区  ›  Chris Bunch

如何创建退出消息

  •  206
  • Chris Bunch  · 技术社区  · 16 年前

    是否有一个单行函数调用退出程序并显示消息?我知道在Perl中,它很简单:

    die("Message goes here")
    

    我厌倦了打这个:

    puts "Message goes here"
    exit
    
    4 回复  |  直到 16 年前
        1
  •  353
  •   the Tin Man    8 年前

    这个 abort 函数执行此操作。例如:

    abort("Message goes here")
    

    注: 中止 消息将写入 STDERR 而不是 puts 会写信给 STDOUT .

        2
  •  23
  •   Jörg W Mittag    16 年前

    如果您想在代码中表示一个实际的错误,可以引发一个 RuntimeError 例外:

    raise RuntimeError, 'Message goes here'
    

    这将打印stacktrace、引发的异常类型和您提供的消息。根据用户的不同,stacktrace可能太可怕,实际消息可能会在噪声中丢失。另一方面,如果由于实际错误而死亡,stacktrace将为调试提供额外的信息。

        3
  •  2
  •   Mike Stone    16 年前

    我从来没有听说过这样的函数,但是它很容易实现…

    def die(msg)
      puts msg
      exit
    end
    

    然后,如果在所有脚本中包含的某个.rb文件中定义了这一点,那么您就是黄金。仅仅因为它不是内置的,并不意味着你不能自己动手;-)

        4
  •  2
  •   Giuse    8 年前

    我在这里寻找一种在程序结束时执行一些代码的方法。
    Found this :

    Kernel.at_exit { puts "sayonara" }
    # do whatever
    # [...]
    # call #exit or #abort or just let the program end
    # calling #exit! will skip the call
    

    多次调用将注册多个处理程序。