Stdout as IO object

J

Jonathan Bale

Okay, real simple question, but somehow I am missing it in the API: how
do create an IO object that represents stdout? I'm using a certain
function that receives writable IO objects and I wanted to pass in the
standard output as a stream.
 
A

Ammar Ali

[Note: parts of this message were removed to make it a legal post.]

Okay, real simple question, but somehow I am missing it in the API: how
do create an IO object that represents stdout? I'm using a certain
function that receives writable IO objects and I wanted to pass in the
standard output as a stream.
Why not just pass $stdout itself?

Ammar
 
B

Brian Candler

Jonathan said:
Okay, real simple question, but somehow I am missing it in the API: how
do create an IO object that represents stdout? I'm using a certain
function that receives writable IO objects and I wanted to pass in the
standard output as a stream.

When your program starts, the constant STDOUT is an open file descriptor
for STDOUT, and the global variable $stdout also points to it.

Using the global variable is the recommended approach, as it adds more
flexibility for pointing it to a different object like a StringIO
without having warnings about constants being redefined.
 
S

skim

[Note: parts of this message were removed to make it a legal post.]

Instead of modifying the global variable $stdout, you could just pass in an
instance of StringIO to your method/class. I passed in two instances of
StringIO to one of my classes for mocking STDIN and STDOUT.
 
J

Jonathan Bale

Brian said:
When your program starts, the constant STDOUT is an open file descriptor
for STDOUT, and the global variable $stdout also points to it.

Using the global variable is the recommended approach, as it adds more
flexibility for pointing it to a different object like a StringIO
without having warnings about constants being redefined.

The $stdout variable works fine. I was a little confused with $stdout at
first, because the documentation I found either does not describe what
it is, or talks about it as a "file descriptor". But it is actually an
IO object:

$ irb
irb(main):001:0> $stdout.class
=> IO
 

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,813
Messages
2,569,697
Members
45,488
Latest member
MohammedHa

Latest Threads

Top