On this page
- io/console
- Example Files
- Modes
- Mode Specified as an Integer
- Mode Specified As a String
- Encodings
- Open Options
- Getline Options
- Position
- Line Number
- What’s Here
- Creating
- Reading
- Writing
- Positioning
- Iterating
- Settings
- Querying
- Buffering
- Low-Level Access
- Other
- Class methods
- Instance methods
- Constants
- Ruby version changes
End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
IO
Expect library adds the IO instance method expect, which does similar act to tcl’s expect extension.
In order to use this method, you must require expect:
require 'expect'
Please see expect for usage.
The IO class is the basis for all input and output in Ruby. An I/O stream may be duplexed (that is, bidirectional), and so may use more than one native operating system stream.
Many of the examples in this section use the File class, the only standard subclass of IO. The two classes are closely associated. Like the File class, the Socket library subclasses from IO (such as TCPSocket or UDPSocket).
The Kernel#open method can create an IO (or File) object for these types of arguments:
-
A plain string represents a filename suitable for the underlying operating system.
-
A string starting with
"|"indicates a subprocess. The remainder of the string following the"|"is invoked as a process with appropriate input/output channels connected to it. -
A string equal to
"|-"will create another Ruby instance as a subprocess.
The IO may be opened with different file modes (read-only, write-only) and encodings for proper conversion. See IO.new for these options. See Kernel#open for details of the various command formats described above.
IO.popen, the Open3 library, or Process#spawn may also be used to communicate with subprocesses through an IO.
Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb" will be opened as "\gumby\ruby\test.rb". When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:
"C:\\gumby\\ruby\\test.rb"
Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.
The global constant ARGF (also accessible as $<) provides an IO-like stream which allows access to all files mentioned on the command line (or STDIN if no files are mentioned). ARGF#path and its alias ARGF#filename are provided to access the name of the file currently being read.
io/console
The io/console extension provides methods for interacting with the console. The console can be accessed from IO.console or the standard input/output/error IO objects.
Requiring io/console adds the following methods:
Example:
require 'io/console' rows, columns = $stdout.winsize puts "Your screen is #{columns} wide and #{rows} tall"
Example Files
Many examples here use these filenames and their corresponding files:
-
t.txt: A text-only file that is assumed to exist via:Exampletext = <<~EOT This is line one. This is the second line. This is the third line. EOT File.write('t.txt', text)
-
t.dat: A data file that is assumed to exist via:Exampledata = "\u9990\u9991\u9992\u9993\u9994" f = File.open('t.dat', 'wb:UTF-16') f.write(data) f.close
-
t.rus: A Russian-language text file that is assumed to exist via:ExampleFile.write('t.rus', "\u{442 435 441 442}")
-
t.tmp: A file that is assumed not to exist.
Modes
A number of IO method calls must or may specify a mode for the stream; the mode determines how stream is to be accessible, including:
-
Whether the stream is to be read-only, write-only, or read-write.
-
Whether the stream is positioned at its beginning or its end.
-
Whether the stream treats data as text-only or binary.
-
The external and internal encodings.
Mode Specified as an Integer
When mode is an integer it must be one or more (combined by bitwise OR (|) of the modes defined in File::Constants:
-
File::RDONLY: Open for reading only. -
File::WRONLY: Open for writing only. -
File::RDWR: Open for reading and writing. -
File::APPEND: Open for appending only. -
File::CREAT: Create file if it does not exist. -
File::EXCL: Raise an exception ifFile::CREATis given and the file exists.
Examples:
File.new('t.txt', File::RDONLY) File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
Note: Method IO#set_encoding does not allow the mode to be specified as an integer.
Mode Specified As a String
When mode is a string it must begin with one of the following:
-
'r': Read-only stream, positioned at the beginning; the stream cannot be changed to writable. -
'w': Write-only stream, positioned at the beginning; the stream cannot be changed to readable. -
'a': Write-only stream, positioned at the end; every write appends to the end; the stream cannot be changed to readable. -
'r+': Read-write stream, positioned at the beginning. -
'w+': Read-write stream, positioned at the end. -
'a+': Read-write stream, positioned at the end.
For a writable file stream (that is, any except read-only), the file is truncated to zero if it exists, and is created if it does not exist.
Examples:
File.open('t.txt', 'r') File.open('t.tmp', 'w')
Either of the following may be suffixed to any of the above:
-
't': Text data; sets the default external encoding toEncoding::UTF_8; on Windows, enables conversion between EOL and CRLF. -
'b': Binary data; sets the default external encoding toEncoding::ASCII_8BIT; on Windows, suppresses conversion between EOL and CRLF.
If neither is given, the stream defaults to text data.
Examples:
File.open('t.txt', 'rt') File.open('t.dat', 'rb')
The following may be suffixed to any writable mode above:
-
'x': Creates the file if it does not exist; raises an exception if the file exists.
Example:
File.open('t.tmp', 'wx')
Finally, the mode string may specify encodings – either external encoding only or both external and internal encodings – by appending one or both encoding names, separated by colons:
f = File.new('t.dat', 'rb') f.external_encoding # => #<Encoding:ASCII-8BIT> f.internal_encoding # => nil f = File.new('t.dat', 'rb:UTF-16') f.external_encoding # => #<Encoding:UTF-16 (dummy)> f.internal_encoding # => nil f = File.new('t.dat', 'rb:UTF-16:UTF-16') f.external_encoding # => #<Encoding:UTF-16 (dummy)> f.internal_encoding # => #<Encoding:UTF-16>
The numerous encoding names are available in array Encoding.name_list:
Encoding.name_list.size # => 175 Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
Encodings
When the external encoding is set, strings read are tagged by that encoding when reading, and strings written are converted to that encoding when writing.
When both external and internal encodings are set, strings read are converted from external to internal encoding, and strings written are converted from internal to external encoding. For further details about transcoding input and output, see Encoding.
If the external encoding is 'BOM|UTF-8', 'BOM|UTF-16LE' or 'BOM|UTF16-BE', Ruby checks for a Unicode BOM in the input document to help determine the encoding. For UTF-16 encodings the file open mode must be binary. If the BOM is found, it is stripped and the external encoding from the BOM is used.
Note that the BOM-style encoding option is case insensitive, so ‘bom|utf-8’ is also valid.)
Open Options
A number of IO methods accept an optional parameter opts, which determines how a new stream is to be opened:
-
:mode: Stream mode. -
:flags: Integer file open flags; Ifmodeis also given, the two are bitwise-ORed. -
:external_encoding: External encoding for the stream. -
:internal_encoding: Internal encoding for the stream.'-'is a synonym for the default internal encoding. If the value isnilno conversion occurs. -
:encoding: Specifies external and internal encodings as'extern:intern'. -
:textmode: If a truthy value, specifies the mode as text-only, binary otherwise. -
:binmode: If a truthy value, specifies the mode as binary, text-only otherwise. -
:autoclose: If a truthy value, specifies that thefdwill close when the stream closes; otherwise it remains open.
Also available are the options offered in String#encode, which may control conversion between external internal encoding.
Getline Options
A number of IO methods accept optional keyword arguments that determine how a stream is to be treated:
-
:chomp: Iftrue, line separators are omitted; default isfalse.
Position
An IO stream has a position, which is the non-negative integer offset (in bytes) in the stream where the next read or write will occur.
Note that a text stream may have multi-byte characters, so a text stream whose position is n (bytes) may not have n characters preceding the current position – there may be fewer.
A new stream is initially positioned:
-
At the beginning (position
0) if its mode is'r','w', or'r+'. -
At the end (position
self.size) if its mode is'a','w+', or'a+'.
Methods to query the position:
-
IO#telland its aliasIO#posreturn the position for an open stream. -
IO#eof?and its aliasIO#eofreturn whether the position is at the end of a readable stream.
Reading from a stream usually changes its position:
f = File.open('t.txt') f.tell # => 0 f.readline # => "This is line one.\n" f.tell # => 19 f.readline # => "This is the second line.\n" f.tell # => 45 f.eof? # => false f.readline # => "Here's the third line.\n" f.eof? # => true
Writing to a stream usually changes its position:
f = File.open('t.tmp', 'w') f.tell # => 0 f.write('foo') # => 3 f.tell # => 3 f.write('bar') # => 3 f.tell # => 6
Iterating over a stream usually changes its position:
f = File.open('t.txt') f.each do |line| p "position=#{f.pos} eof?=#{f.eof?} line=#{line}" end
Output:
"position=19 eof?=false line=This is line one.\n" "position=45 eof?=false line=This is the second line.\n" "position=70 eof?=true line=This is the third line.\n"
The position may also be changed by certain other methods:
-
IO#pos=andIO#seekchange the position to a specified offset. -
IO#rewindchanges the position to the beginning.
Line Number
A readable IO stream has a line number, which is the non-negative integer line number in the stream where the next read will occur.
A new stream is initially has line number 0.
Method IO#lineno returns the line number.
Reading lines from a stream usually changes its line number:
f = File.open('t.txt', 'r') f.lineno # => 0 f.readline # => "This is line one.\n" f.lineno # => 1 f.readline # => "This is the second line.\n" f.lineno # => 2 f.readline # => "Here's the third line.\n" f.lineno # => 3 f.eof? # => true
Iterating over lines in a stream usually changes its line number:
f = File.open('t.txt') f.each_line do |line| p "position=#{f.pos} eof?=#{f.eof?} line=#{line}" end
Output:
"position=19 eof?=false line=This is line one.\n" "position=45 eof?=false line=This is the second line.\n" "position=70 eof?=true line=This is the third line.\n"
What’s Here
First, what’s elsewhere. Class IO:
-
Inherits from class Object.
-
Includes module Enumerable, which provides dozens of additional methods.
Here, class IO provides methods that are useful for:
Creating
::open-
Creates a new IO object.
::pipe-
Creates a connected pair of reader and writer IO objects.
::popen-
Creates an IO object to interact with a subprocess.
::select-
Selects which given IO instances are ready for reading,
writing, or have pending exceptions.
Reading
::binread-
Returns a binary string with all or a subset of bytes from the given file.
::read-
Returns a string with all or a subset of bytes from the given file.
::readlines-
Returns an array of strings, which are the lines from the given file.
getbyte-
Returns the next 8-bit byte read from
selfas an integer.
getc-
Returns the next character read from
selfas a string.
gets-
Returns the line read from
self.
pread-
Returns all or the next n bytes read from
self, not updating the receiver’s offset.
read-
Returns all remaining or the next n bytes read from
selffor a given n.
read_nonblock-
the next n bytes read from
selffor a given n, in non-block mode.
readline-
Returns the next line read from
self; same as getline, but raises an exception of end-of-file.
readlines-
Returns an array of all lines read read from
self.
readpartial-
Returns up to the given number of bytes from
self.
Writing
::binwrite-
Writes the given string to the file at the given filepath, in binary mode.
::write-
Writes the given string to
self.
- ::<<
-
Appends the given string to
self.
print-
Prints last read line or given objects to
self.
printf-
Writes to
selfbased on the given format string and objects.
putc-
Writes a character to
self.
puts-
Writes lines to
self, making sure line ends with a newline.
pwrite-
Writes the given string at the given offset, not updating the receiver’s offset.
write-
Writes one or more given strings to
self.
write_nonblock-
Writes one or more given strings to
selfin non-blocking mode.
Positioning
lineno-
Returns the current line number in
self.
lineno=-
Sets the line number is
self.
pos=-
Sets the byte offset in
self.
reopen-
Reassociates
selfwith a new or existing IO stream.
rewind-
Positions
selfto the beginning of input.
seek-
Sets the offset for
selfrelative to given position.
Iterating
::foreach-
Yields each line of given file to the block.
each_byte-
Calls the given block with each successive byte in
selfas an integer.
each_char-
Calls the given block with each successive character in
selfas a string.
each_codepoint-
Calls the given block with each successive codepoint in
selfas an integer.
Settings
autoclose=-
Sets whether
selfauto-closes.
binmode-
Sets
selfto binary mode.
close-
Closes
self.
close_on_exec=-
Sets the close-on-exec flag.
close_read-
Closes
selffor reading.
close_write-
Closes
selffor writing.
set_encoding-
Sets the encoding for
self.
set_encoding_by_bom-
Sets the encoding for
self, based on its Unicode byte-order-mark.
sync=-
Sets the sync-mode to the given value.
Querying
autoclose?-
Returns whether
selfauto-closes.
binmode?-
Returns whether
selfis in binary mode.
close_on_exec?-
Returns the close-on-exec flag for
self.
closed?-
Returns whether
selfis closed.
external_encoding-
Returns the external encoding object for
self.
internal_encoding-
Returns the internal encoding object for
self.
stat-
Returns the
File::Statobject containing status information forself.
sync-
Returns whether
selfis in sync-mode.
- tty (aliased as
isatty) -
Returns whether
selfis a terminal.
- tty (aliased as
Buffering
fdatasync-
Immediately writes all buffered data in
selfto disk.
flush-
Flushes any buffered data within
selfto the underlying operating system.
fsync-
Immediately writes all buffered data and attributes in
selfto disk.
ungetbyte-
Prepends buffer for
selfwith given integer byte or string.
ungetc-
Prepends buffer for
selfwith given string.
Low-Level Access
::sysopen-
Opens the file given by its path, returning the integer file descriptor.
advise-
Announces the intention to access data from
selfin a specific way.
fcntl-
Passes a low-level command to the file specified by the given file descriptor.
ioctl-
Passes a low-level command to the device specified by the given file descriptor.
sysread-
Returns up to the next n bytes read from self using a low-level read.
sysseek-
Sets the offset for
self.
syswrite-
Writes the given string to
selfusing a low-level write.
Other
::copy_stream-
Copies data from a source to a destination, each of which is a filepath or an IO-like object.
::try_convert-
Returns a new IO object resulting from converting the given object.
inspect-
Returns the string representation of
self.
Class methods 18
Instance methods 112
Ruby version changes 2
-
3.0
-
IO#nonblock?now defaults totrue. [Feature #16786] -
IO#wait_readable,IO#wait_writable,IO#read,IO#writeand other related methods (e.g.IO#puts,IO#gets) may invoke the scheduler hook io_wait(io, events, timeout) in a non-blocking execution context. [Feature #16786]
-