2012-04-15 46 views

回答

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' 
+0

我可以提供這個小的改進? http://pastebin.com/rikRNgzq – 2012-04-15 17:43:51

+0

順便說一句,我的版本(在答案中)實際上打印了一些東西,同時緩存它們。 :)不知道這對OP是否重要。 – 2012-04-15 17:45:25

+0

@Sergio不錯的功能,但不要叫它'with_cached_output' - 它不是緩存,它是重定向。 – 2012-04-16 05:38:14

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"