Skip to content

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

class method

IO.read

IO.read(name, [length [, offset]] [, opt]) → string
File.read(name, [length [, offset]] [, opt]) → string

Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest of the file). read ensures the file is closed before returning.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.read to disable the behavior of subprocess invocation.

Options

The options hash accepts the following keys:

:encoding

string or encoding

Specifies the encoding of the read string. :encoding will be ignored if length is specified. See Encoding.aliases for possible encodings.

:mode

string or integer

Specifies the mode argument for open(). It must start with an “r”, otherwise it will cause an error. See IO.new for the list of possible modes.

:open_args

array

Specifies arguments for open() as an array. This key can not be used in combination with either :encoding or :mode.

Examples:

Example
File.read("testfile")            #=> "This is line one\nThis is line two\nThis is line three\nAnd so on...\n"
File.read("testfile", 20)        #=> "This is line one\nThi"
File.read("testfile", 20, 10)    #=> "ne one\nThis is line "
File.read("binfile", mode: "rb") #=> "\xF7\x00\x00\x0E\x12"
IO.read("|ls -a")                #=> ".\n..\n"...
See also #read .popen .readlines .pipe also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0