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



如何缓存"看跌"和"打印"结果,并将其保存到变量中。就像 php 中的ob_start()ob_get_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 # => "foonbarn"
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'

最新更新