1

如何缓存“puts”和“print”结果,并将其保存到变量中。喜欢ob_start()ob_get_contents()在 php.ini 中。

4

2 回答 2

2

有些人可能会发布巧妙的解决方案,这些解决方案利用了我不熟悉的 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"
于 2012-04-15T17:15:24.547 回答
1
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'
于 2012-04-15T17:38:19.757 回答