Skip to content

End of Life Ruby 3.0 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

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.

Example
IO.foreach("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.1