我想在一个块的持续时间内暂时重定向Ruby脚本中的stderr,确保在块的末尾将其重置为原始值.

在ruby文档中,我很难找到如何做到这一点.

推荐答案

在Ruby中,$stderr指的是currently used作为stderr的输出流,而STDERR指的是default stderr流.很容易将不同的输出流临时分配给$stderr.

require "stringio"

def capture_stderr
  # The output stream must be an IO-like object. In this case we capture it in
  # an in-memory IO object so we can return the string value. You can assign any
  # IO object here.
  previous_stderr, $stderr = $stderr, StringIO.new
  yield
  $stderr.string
ensure
  # Restore the previous value of stderr (typically equal to STDERR).
  $stderr = previous_stderr
end

现在,您可以执行以下操作:

captured_output = capture_stderr do
  # Does not output anything directly.
  $stderr.puts "test"
end

captured_output
#=> "test\n"

同样的原理也适用于$stdoutSTDOUT.

Ruby相关问答推荐

有没有办法把条件语句写得更干净?

在 ruby​​ 中提取文档中的主题标签和部分

如何解密在 sjcl.js 中使用 ruby​​ 创建的 AES-256-GCM

我可以在 Ruby 的 heredoc 中访问变量吗?

Rspec: expectvsexpect什么区别?

如何在Ruby中从字符串中go 除前导和尾随引号

如何使用 yardoc 列出未记录的模块/类/常量/方法?

有没有办法在 RSpec 中取消存根?

对于基于 GitHub 的 gem,强制Bundle 安装使用 https:// 而不是 git://

理解 Ruby 中的私有方法

Ruby 1.9 哈希,键中有破折号

判断是否在 SASS 中定义了变量

在 Ruby 中查找内存泄漏的原因

Ruby 异常 - 为什么是else?

`File` 对象访问模式的区别(即 w+, r+)

如何在没有警告的情况下重新定义 Ruby 常量?

如何在 jekyll markdown 博客中包含视频

Ruby 中的 each 和 collect 方法有什么不同

以小时为单位的时差

检索/列出 Redis 数据库中的所有键/值对