Skip to content

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

class method

IO.foreach

IO.foreach(name, sep=$/ [, getline_args, open_args]) {|line| block } → nil
IO.foreach(name, limit [, getline_args, open_args]) {|line| block } → nil
IO.foreach(name, sep, limit [, getline_args, open_args]) {|line| block } → nil
IO.foreach(...) → an_enumerator
File.foreach(name, sep=$/ [, getline_args, open_args]) {|line| block } → nil
File.foreach(name, limit [, getline_args, open_args]) {|line| block } → nil
File.foreach(name, sep, limit [, getline_args, open_args]) {|line| block } → nil
File.foreach(...) → an_enumerator

Executes the block for every line in the named I/O port, where lines are separated by sep.

If no block is given, an enumerator is returned instead.

If name starts with a pipe character ("|") and the receiver is the IO class, a subprocess is created in the same way as Kernel#open, and its output is returned. Consider to use File.foreach to disable the behavior of subprocess invocation.

Example
File.foreach("testfile") {|x| print "GOT ", x }
IO.foreach("| cat testfile") {|x| print "GOT ", x }

produces:

Example
GOT This is line one
GOT This is line two
GOT This is line three
GOT And so on...

If the last argument is a hash, it’s the keyword argument to open. See IO.readlines for details about getline_args. And see also IO.read for details about open_args.

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