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.foreach

IO.foreach(path, sep = $/, **opts) {|line| block } → nil
IO.foreach(path, limit, **opts) {|line| block } → nil
IO.foreach(path, sep, limit, **opts) {|line| block } → nil
IO.foreach(command, sep = $/, **opts) {|line| block } → nil
IO.foreach(command, limit, **opts) {|line| block } → nil
IO.foreach(command, sep, limit, **opts) {|line| block } → nil
IO.foreach(...) → an_enumerator

Calls the block with each successive line 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 that is one of the following:

  • Path: if self is a subclass of IO (File, for example), or if the string does not start with the pipe character ('|'), the string is the path to a file.

  • Command: if self is the class IO, and if the string starts with the pipe character, the rest of the string is a command to be executed as a subprocess. This usage has potential security vulnerabilities if called with untrusted input; see Command Injection.

With only argument path given, parses lines from the file at the given path, as determined by the default line separator, and calls the block with each successive line:

Example
File.foreach('t.txt') {|line| p line }

Output: the same as above.

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
File.foreach('t.txt', 'li') {|line| p line }

Output:

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

Each paragraph:

Example
File.foreach('t.txt', '') {|paragraph| p paragraph }

Output:

Example
"First line\nSecond line\n\n"
"Third 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
File.foreach('t.txt', 7) {|line| p line }

Output:

Example
"First l"
"ine\n"
"Second "
"line\n"
"\n"
"Third l"
"ine\n"
"Fourth l"
"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:

Returns an Enumerator if no block is given.

See also .default_console_size .for_fd .copy_stream .new also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0