Ruby 如何缓存输出?(如php中的ob_start())

Ruby 如何缓存输出?(如php中的ob_start()),ruby,Ruby,如何缓存“放置”和“打印”结果,并将其保存到变量。像php中的ob\u start()和ob\u get\u contents()。一些人可能会发布聪明的解决方案,利用我不熟悉的ruby标准库的一部分。我只能给你一个小脏猴子补丁: module Kernel alias_method :old_puts, :puts def puts txt @cached_output ||= '' @cached_output += "#{txt}\n" old_puts

如何缓存“放置”和“打印”结果,并将其保存到变量。像php中的
ob\u start()
ob\u get\u contents()

一些人可能会发布聪明的解决方案,利用我不熟悉的ruby标准库的一部分。我只能给你一个小脏猴子补丁:

module Kernel
  alias_method :old_puts, :puts

  def puts txt
    @cached_output ||= ''
    @cached_output += "#{txt}\n"
    old_puts txt
  end

  def cached_output
    @cached_output
  end
end

puts 'foo'
puts 'bar'
cached_output # => "foo\nbar\n"

顺便说一句,我的版本(在答案中)实际上是在缓存内容的同时打印内容。:)不确定它对OP是否重要。@Sergio函数很好,但不要用缓存的输出调用它,它不是缓存,而是重定向。
require 'stringio'

save_so, $stdout = $stdout, StringIO.new(' ', 'w')
puts 'how now brown cow'
my_so, $stdout = $stdout, save_so

p [:saved_result, my_so.string]
puts 'and this works once again'