Skip to content

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

instance method

IO#each_line

each_line(sep = $/, chomp: false) {|line| ... } → self
each_line(limit, chomp: false) {|line| ... } → self
each_line(sep, limit, chomp: false) {|line| ... } → self
each_line → enumerator

Alias of #each

Calls the block with each remaining line read from the stream; returns self. Does nothing if already at end-of-stream; See Line IO.

With no arguments given, reads lines as determined by line separator $/:

Example
f = File.new('t.txt')
f.each_line {|line| p line }
f.each_line {|line| fail 'Cannot happen' }
f.close

Output:

Example
"First line\n"
"Second line\n"
"\n"
"Fourth line\n"
"Fifth line\n"

With only string argument sep given, reads lines as determined by line separator sep; see Line Separator:

Example
f = File.new('t.txt')
f.each_line('li') {|line| p line }
f.close

Output:

Example
"First li"
"ne\nSecond li"
"ne\n\nFourth li"
"ne\nFifth li"
"ne\n"

The two special values for sep are honored:

Example
f = File.new('t.txt')
# Get all into one string.
f.each_line(nil) {|line| p line }
f.close

Output:

Example
"First line\nSecond line\n\nFourth line\nFifth line\n"

f.rewind
# Get paragraphs (up to two line separators).
f.each_line('') {|line| p line }

Output:

Example
"First line\nSecond line\n\n"
"Fourth line\nFifth line\n"

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

Example
f = File.new('t.txt')
f.each_line(8) {|line| p line }
f.close

Output:

Example
"First li"
"ne\n"
"Second l"
"ine\n"
"\n"
"Fourth l"
"ine\n"
"Fifth li"
"ne\n"

With arguments sep and limit given, combines the two behaviors:

  • Calls with the next line as determined by line separator sep.

  • But returns no more bytes than are allowed by the limit.

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

Example
f = File.new('t.txt')
f.each_line(chomp: true) {|line| p line }
f.close

Output:

Example
"First line"
"Second line"
""
"Fourth line"
"Fifth line"

Returns an Enumerator if no block is given.

IO#each is an alias for IO#each_line.

See also #each #each_codepoint #echo= #each_char also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0