Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

IO.readlines

(::path name, ?::String sep, ?::Integer limit, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String, ?chomp: ::boolish) -> ::Array[::String]
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.

The first argument must be a string that is the path to a file.

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"]

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 Separator and 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, combines the two behaviors (see Line Separator and Line Limit).

Optional keyword arguments opts specify:

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