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

IO#reopen

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:

See also #ready? #rewind #readpartial #scroll_backward also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0