Skip to content

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

class method

IO.readlines

IO.readlines(command, sep = $/, **opts) → array
IO.readlines(command, limit, **opts) → array
IO.readlines(command, sep, limit, **opts) → array
IO.readlines(path, sep = $/, **opts) → array
IO.readlines(path, limit, **opts) → array
IO.readlines(path, sep, limit, **opts) → array

Returns an array of all lines read from the stream.

When called from class IO (but not subclasses of IO), this method has potential security vulnerabilities if called with untrusted input; see Command Injection.

The first argument must be a string; its meaning depends on whether it starts with the pipe character ('|'):

  • If so (and if self is IO), the rest of the string is a command to be executed as a subprocess.

  • Otherwise, the string is the path to a file.

With only argument command given, executes the command in a shell, parses its $stdout into lines, as determined by the default line separator, and returns those lines in an array:

Example
IO.readlines('| cat t.txt')
# => ["First line\n", "Second line\n", "\n", "Third line\n", "Fourth line\n"]

With only argument path given, parses lines from the file at the given path, as determined by the default line separator, and returns those lines in an array:

Example
IO.readlines('t.txt')
# => ["First line\n", "Second line\n", "\n", "Third line\n", "Fourth line\n"]

For both forms, command and path, the remaining arguments are the same.

With argument sep given, parses lines as determined by that line separator (see Line Separator):

Example
# Ordinary separator.
IO.readlines('t.txt', 'li')
# =>["First li", "ne\nSecond li", "ne\n\nThird li", "ne\nFourth li", "ne\n"]
# Get-paragraphs separator.
IO.readlines('t.txt', '')
# => ["First line\nSecond line\n\n", "Third line\nFourth line\n"]
# Get-all separator.
IO.readlines('t.txt', nil)
# => ["First line\nSecond line\n\nThird line\nFourth line\n"]

With argument limit given, parses lines as determined by the default line separator and the given line-length limit (see Line Limit):

Example
IO.readlines('t.txt', 7)
# => ["First l", "ine\n", "Second ", "line\n", "\n", "Third l", "ine\n", "Fourth ", "line\n"]

With arguments sep and limit given, parses lines as determined by the given line separator and the given line-length limit (see Line Separator and Line Limit):

Optional keyword arguments opts specify:

See also #readlines .read .select .popen also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0