open(*args) 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”).

The mode_enc is either a string or an integer. If it is an integer, it must be bitwise-or of open(2) flags, such as File::RDWR or File::EXCL. If it is a string, it is either “mode”, “mode:ext_enc”, or “mode:ext_enc:int_enc”. The mode is one of the following:

r: read (default)
w: write
a: append

The mode can be followed by “b” (means binary-mode), or “+” (means both reading and writing allowed) or both. If ext_enc (external encoding) is specified, read string will be tagged by the encoding in reading, and output string will be converted to the specified encoding in writing. If ext_enc starts with ‘BOM|’, check whether the input has a BOM. If there is a BOM, strip it and set external encoding as what the BOM tells. If there is no BOM, use ext_enc without ‘BOM|’. If two encoding names, ext_enc and int_enc (external encoding and internal encoding), are specified, the read string is converted from ext_enc to int_enc then tagged with the int_enc in read mode, and in write mode, the output string will be converted from int_enc to ext_enc before writing.

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