How do I temporarily redirect stderr in Ruby?

后端 未结 4 1370
暗喜
暗喜 2020-11-28 07:34

I\'d like to temporarily redirect stderr in a Ruby script for the duration of a block, ensuring that I reset it to its original value at the end of the block.

I had

4条回答
  •  长情又很酷
    2020-11-28 07:50

    Essentially the same as @molf's answer, and has the same usage:

    require "stringio"
    def capture_stderr
      real_stderr, $stderr = $stderr, StringIO.new
      yield
      $stderr.string
    ensure
      $stderr = real_stderr
    end
    

    It uses StringIO very slightly more concisely, and preserves $stderr as whatever it was before capture_stderr was called.

提交回复
热议问题