How to capture eval's stdout in 1.8?

S

Stephen Waits

My searches have come up empty, and most of what I found refers to 1.6
(assigning $defout to a StringIO instance).

However, under 1.8 this doesn't work because:

a) assignment to $stdout (which deprecates $defout) is deprecated
b) $stdout.reopen( StringIO ) doesn't work as reopen expects a true IO
instance

And, for that matter, I couldn't even get it to redirect to a File.

Seems like it should be easy.. anyone?

Thanks,
Steve
 
L

Logan Capaldo

--Apple-Mail-27-240121866
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
delsp=yes;
format=flowed


a) assignment to $stdout (which deprecates $defout) is deprecated

Are you sure? -w gives me no Object#type is deprecated use
Object#class style warnings

% cat moving_stdout.rb
require 'stringio'
old_stdout = $stdout
$stdout = StringIO.new
puts "Hello"
old_stdout.puts "The real console"
old_stdout.puts "Caputured stdout: #{$stdout.string}"
$stdout = old_stdout
puts "Back to normal"

% ruby -w moving_stdout.rb
The real console
Caputured stdout: Hello
Back to normal

% ruby -v
ruby 1.8.4 (2005-12-24) [powerpc-darwin8.4.0]




--Apple-Mail-27-240121866--
 
S

Stephen Waits

Stephen said:
My searches have come up empty, and most of what I found refers to 1.6
(assigning $defout to a StringIO instance).

However, under 1.8 this doesn't work because:

a) assignment to $stdout (which deprecates $defout) is deprecated
b) $stdout.reopen( StringIO ) doesn't work as reopen expects a true IO
instance

And, for that matter, I couldn't even get it to redirect to a File.

Seems like it should be easy.. anyone?

Thanks,
Steve

Hmm.. I still haven't found the right solution. I'm starting to worry
that this might not be possible in 1.8!

--Steve
 
S

Stephen Waits

Logan said:
Are you sure? -w gives me no Object#type is deprecated use Object#class
style warnings

Shame on me. I followed the docs too closely, which all say assignment
is deprecated, use .reopen.

Anyway, it works!

Thanks Logan.

--Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top