How do I temporarily redirect stderr in Ruby?

后端 未结 4 1373
暗喜
暗喜 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 08:14

    Here is a more abstract solution (credit goes to David Heinemeier Hansson):

    def silence_streams(*streams)
      on_hold = streams.collect { |stream| stream.dup }
      streams.each do |stream|
        stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
        stream.sync = true
      end
      yield
    ensure
      streams.each_with_index do |stream, i|
        stream.reopen(on_hold[i])
      end
    end
    

    Usage:

    silence_streams(STDERR) { do_something }
    

提交回复
热议问题