Skip to content
On this page

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

class · Ruby 3.1

IO

< Object include Enumerable include File::Constants 112 instance methods 18 class methods

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:

Example
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:

Example
"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:

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:

    Example
    text = <<~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:

    Example
    data = "\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:

    Example
    File.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:

Examples:

Example
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:

Example
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 to Encoding::UTF_8; on Windows, enables conversion between EOL and CRLF.

  • 'b': Binary data; sets the default external encoding to Encoding::ASCII_8BIT; on Windows, suppresses conversion between EOL and CRLF.

If neither is given, the stream defaults to text data.

Examples:

Example
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:

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:

Example
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:

Example
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; If mode is 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 is nil no 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 the fd will 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: If true, line separators are omitted; default is false.

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#tell and its alias IO#pos return the position for an open stream.

  • IO#eof? and its alias IO#eof return whether the position is at the end of a readable stream.

Reading from a stream usually changes its position:

Example
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:

Example
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:

Example
f = File.open('t.txt')
f.each do |line|
  p "position=#{f.pos} eof?=#{f.eof?} line=#{line}"
end

Output:

Example
"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:

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:

Example
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:

Example
f = File.open('t.txt')
f.each_line do |line|
  p "position=#{f.pos} eof?=#{f.eof?} line=#{line}"
end

Output:

Example
"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:

Here, class IO provides methods that are useful for:

Creating

  • ::new (aliased as ::for_fd)

    Creates and returns a new IO object for the given integer file descriptor.

  • ::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 self as an integer.

  • getc

    Returns the next character read from self as 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 self for a given n.

  • read_nonblock

    the next n bytes read from self for a given n, in non-block mode.

  • readbyte

    Returns the next byte read from self; same as getbyte, but raises an exception on end-of-file.

  • readchar

    Returns the next character read from self; same as getc, but raises an exception on end-of-file.

  • 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 self based 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 self in non-blocking mode.

Positioning

  • lineno

    Returns the current line number in self.

  • lineno=

    Sets the line number is self.

  • pos (aliased as tell)

    Returns the current byte offset in self.

  • pos=

    Sets the byte offset in self.

  • reopen

    Reassociates self with a new or existing IO stream.

  • rewind

    Positions self to the beginning of input.

  • seek

    Sets the offset for self relative to given position.

Iterating

  • ::foreach

    Yields each line of given file to the block.

  • each (aliased as each_line)

    Calls the given block with each successive line in self.

  • each_byte

    Calls the given block with each successive byte in self as an integer.

  • each_char

    Calls the given block with each successive character in self as a string.

  • each_codepoint

    Calls the given block with each successive codepoint in self as an integer.

Settings

Querying

  • autoclose?

    Returns whether self auto-closes.

  • binmode?

    Returns whether self is in binary mode.

  • close_on_exec?

    Returns the close-on-exec flag for self.

  • closed?

    Returns whether self is closed.

  • eof? (aliased as eof)

    Returns whether self is at end-of-file.

  • external_encoding

    Returns the external encoding object for self.

  • fileno (aliased as to_i)

    Returns the integer file descriptor for self

  • internal_encoding

    Returns the internal encoding object for self.

  • pid

    Returns the process ID of a child process associated with self, if self was created by ::popen.

  • stat

    Returns the File::Stat object containing status information for self.

  • sync

    Returns whether self is in sync-mode.

  • tty (aliased as isatty)

    Returns whether self is a terminal.

Buffering

  • fdatasync

    Immediately writes all buffered data in self to disk.

  • flush

    Flushes any buffered data within self to the underlying operating system.

  • fsync

    Immediately writes all buffered data and attributes in self to disk.

  • ungetbyte

    Prepends buffer for self with given integer byte or string.

  • ungetc

    Prepends buffer for self with 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 self in 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 self using 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

Constants
No documentation available
No documentation available

Set I/O position from the current position

Set I/O position to the next location containing data

Set I/O position from the end

Set I/O position to the next hole

Set I/O position from the beginning

No documentation available

Ruby version changes 2

  1. 3.0