Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Kernel#open

open(path, mode = 'r', perm = 0666, **opts) → io or nil
open(path, mode = 'r', perm = 0666, **opts) {|io| ... } → obj

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

Required string argument path determines which of the following occurs:

  • The file at the specified path is opened.

  • The process forks.

  • A subprocess is created.

Each of these is detailed below.

File Opened

If path does not start with a pipe character ('|'), a file stream is opened with File.open(path, mode, perm, **opts).

With no block given, file stream is returned:

Example
open('t.txt') # => #<File:t.txt>

With a block given, calls the block with the open file stream, then closes the stream:

Example
open('t.txt') {|f| p f } # => #<File:t.txt (closed)>

Output:

Example
#<File:t.txt>

See File.open for details.

Process Forked

If path is the 2-character string '|-', the process forks and the child process is connected to the parent.

With no block given:

Example
io = open('|-')
if io
  $stderr.puts "In parent, child pid is #{io.pid}."
else
  $stderr.puts "In child, pid is #{$$}."
end

Output:

In parent, child pid is 27903.
In child, pid is 27903.

With a block given:

Example
open('|-') do |io|
  if io
    $stderr.puts "In parent, child pid is #{io.pid}."
  else
    $stderr.puts "In child, pid is #{$$}."
  end
end

Output:

In parent, child pid is 28427.
In child, pid is 28427.

Subprocess Created

If path is '|command' ('command' != '-'), a new subprocess runs the command; its open stream is returned. Note that the command may be processed by shell if it contains shell metacharacters.

With no block given:

Example
io = open('|echo "Hi!"') # => #<IO:fd 12>
print io.gets
io.close

Output:

Example
"Hi!"

With a block given, calls the block with the stream, then closes the stream:

Example
open('|echo "Hi!"') do |io|
  print io.gets
end

Output:

Example
"Hi!"
See also #__method__ #p #loop #Pathname also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0