Skip to content

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

instance method

ARGF#each_line

ARGF.each_line(sep=$/) {|line| block } → ARGF
ARGF.each_line(sep=$/, limit) {|line| block } → ARGF
ARGF.each_line(...) → an_enumerator

Alias of #each

Returns an enumerator which iterates over each line (separated by sep, which defaults to your platform’s newline character) of each file in ARGV. If a block is supplied, each line in turn will be yielded to the block, otherwise an enumerator is returned. The optional limit argument is an Integer specifying the maximum length of each line; longer lines will be split according to this limit.

This method allows you to treat the files supplied on the command line as a single file consisting of the concatenation of each named file. After the last line of the first file has been returned, the first line of the second file is returned. The ARGF.filename and ARGF.lineno methods can be used to determine the filename of the current line and line number of the whole input, respectively.

For example, the following code prints out each line of each named file prefixed with its line number, displaying the filename once per file:

Example
ARGF.each_line do |line|
  puts ARGF.filename if ARGF.file.lineno == 1
  puts "#{ARGF.file.lineno}: #{line}"
end

While the following code prints only the first file’s name at first, and the contents with line number counted through all named files.

Example
ARGF.each_line do |line|
  puts ARGF.filename if ARGF.lineno == 1
  puts "#{ARGF.lineno}: #{line}"
end
See also #each #each_codepoint #eof #each_char also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0