open(...) public

Creates an IO object connected to the given stream, file, or subprocess.

If path does not start with a pipe character (``|’’), treat it as the name of a file to open using the specified mode (defaulting to ``r''). (See the table of valid modes on page 331.) If a file is being created, its initial permissions may be set using the integer third parameter.

If a block is specified, it will be invoked with the File object as a parameter, and the file will be automatically closed when the block terminates. The call returns the value of the block.

If path starts with a pipe character, a subprocess is created, connected to the caller by a pair of pipes. The returned IO object may be used to write to the standard input and read from the standard output of this subprocess. If the command following the ``|’’ is a single minus sign, Ruby forks, and this subprocess is connected to the parent. In the subprocess, the open call returns nil. If the command is not ``-’’, the subprocess runs the command. If a block is associated with an open("|-") call, that block will be run twice—once in the parent and once in the child. The block parameter will be an IO object in the parent and nil in the child. The parent’s IO object will be connected to the child’s $stdin and $stdout. The subprocess will be terminated at the end of the block.

   open("testfile") do |f|
     print f.gets
   end

produces:

   This is line one

Open a subprocess and read its output:

   cmd = open("|date")
   print cmd.gets
   cmd.close

produces:

   Wed Apr  9 08:56:31 CDT 2003

Open a subprocess running the same Ruby program:

   f = open("|-", "w+")
   if f == nil
     puts "in Child"
     exit
   else
     puts "Got: #{f.gets}"
   end

produces:

   Got: in Child

Open a subprocess using a block to receive the I/O object:

   open("|-") do |f|
     if f == nil
       puts "in Child"
     else
       puts "Got: #{f.gets}"
     end
   end

produces:

   Got: in Child
Show source
Register or log in to add new notes.
April 23, 2009
0 thanks

See Also: IO Class Methods

There are other more specific methods defined in the IO class: IO.open for files, IO.popen for pipes.