I have seen much talking about this topic, but no working code!

I want to capture all output from [ruby, child_processes].
How can I do this ?


When I run my code I get this output.. 
But this is not what I am expecting.

> ruby main.rb
stderr
stdout
defout
OK 1
OK 2
>

I want output like this.. what am I doing wrong ?
OK 1
OK stderr
OK stdout
OK defout
OK 2



> cat main.rb
require 'stringio'

def capture
    raise unless block_given?
    a, b, c = $defout, $stderr, $stdout
    buf = StringIO.new(s = "", "w")
    begin
        $defout, $stderr, $stdout = buf
        yield
    ensure
                buf.close
        $defout, $stderr, $stdout = a, b, c
    end
        s.split(/\n/)
end

res = capture {
        puts "1"
        system("ruby output.rb")  # BOOM - Output is not being captured?
        puts "2"
}
puts res.collect{|s| "OK "+s }.join("\n")
> cat output.rb
$stderr.puts "stderr"
$stdout.puts "stdout"
$defout.puts "defout"
>


--
Simon Strandgaard