Skip to content

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

class method

IO.foreach

(::path path, ?::String sep, ?::Integer limit, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String, ?chomp: ::boolish) { (::String line) -> void } -> nil
(::path path, ?::String sep, ?::Integer limit, ?external_encoding: ::String | ::Encoding | nil, ?internal_encoding: ::String | ::Encoding | nil, ?encoding: ::String | ::Encoding | nil, ?textmode: ::boolish, ?binmode: ::boolish, ?autoclose: ::boolish, ?mode: ::String, ?chomp: ::boolish) -> ::Enumerator[::String, nil]
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(...) → an_enumerator

Calls the block with each successive line read from the stream.

The first argument must be a string that is the path to a file.

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 Separator and 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, combines the two behaviors (see Line Separator and Line Limit).

Optional keyword arguments opts specify:

Returns an Enumerator if no block is given.

See also .copy_stream .for_fd .console .new also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0