Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

IO#reopen

(::IO other_IO_or_path) -> ::IO
(::String other_IO_or_path, ?::String mode_str) -> ::IO
reopen(other_io) → self
reopen(path, mode = 'r', **opts) → self

Reassociates the stream with another stream, which may be of a different class. This method may be used to redirect an existing stream to a new destination.

With argument other_io given, reassociates with that stream:

Example
# Redirect $stdin from a file.
f = File.open('t.txt')
$stdin.reopen(f)
f.close

# Redirect $stdout to a file.
f = File.open('t.tmp', 'w')
$stdout.reopen(f)
f.close

With argument path given, reassociates with a new stream to that file path:

Example
$stdin.reopen('t.txt')
$stdout.reopen('t.tmp', 'w')

Optional keyword arguments opts specify: