Skip to content
instance method

IO#readlines

(?::String sep, ?::Integer limit, ?chomp: ::boolish) -> ::Array[::String]
readlines(sep = $/, chomp: false) → array
readlines(limit, chomp: false) → array
readlines(sep, limit, chomp: false) → array

Reads and returns all remaining line from the stream; does not modify $_. See Line IO.

With no arguments given, returns lines as determined by line separator $/, or nil if none:

Example
f = File.new('t.txt')
f.readlines
# => ["First line\n", "Second line\n", "\n", "Fourth line\n", "Fifth line\n"]
f.readlines # => []
f.close

With only string argument sep given, returns lines as determined by line separator sep, or nil if none; see Line Separator:

Example
f = File.new('t.txt')
f.readlines('li')
# => ["First li", "ne\nSecond li", "ne\n\nFourth li", "ne\nFifth li", "ne\n"]
f.close

The two special values for sep are honored:

Example
f = File.new('t.txt')
# Get all into one string.
f.readlines(nil)
# => ["First line\nSecond line\n\nFourth line\nFifth line\n"]
# Get paragraphs (up to two line separators).
f.rewind
f.readlines('')
# => ["First line\nSecond line\n\n", "Fourth line\nFifth line\n"]
f.close

With only integer argument limit given, limits the number of bytes in each line; see Line Limit:

Example
f = File.new('t.txt')
f.readlines(8)
# => ["First li", "ne\n", "Second l", "ine\n", "\n", "Fourth l", "ine\n", "Fifth li", "ne\n"]
f.close

With arguments sep and limit given, combines the two behaviors (see Line Separator and Line Limit).

Optional keyword argument chomp specifies whether line separators are to be omitted:

Example
f = File.new('t.txt')
f.readlines(chomp: true)
# => ["First line", "Second line", "", "Fourth line", "Fifth line"]
f.close
See also .readlines #readline #read_nonblock #readchar also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0