Method: IO.foreach

Defined in:
io.c

.foreach(path, sep = $/, **opts) {|line| ... } ⇒ nil .foreach(path, limit, **opts) {|line| ... } ⇒ nil .foreach(path, sep, limit, **opts) {|line| ... } ⇒ nil .foreach(...) ⇒ Object

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 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:

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):

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

Output:

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

Each paragraph:

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

Output:

"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):

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

Output:

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

Overloads:

  • .foreach(path, sep = $/, **opts) {|line| ... } ⇒ nil

    Yields:

    • (line)

    Returns:

    • (nil)
  • .foreach(path, limit, **opts) {|line| ... } ⇒ nil

    Yields:

    • (line)

    Returns:

    • (nil)
  • .foreach(path, sep, limit, **opts) {|line| ... } ⇒ nil

    Yields:

    • (line)

    Returns:

    • (nil)

12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
# File 'io.c', line 12083

static VALUE
rb_io_s_foreach(int argc, VALUE *argv, VALUE self)
{
    VALUE opt;
    int orig_argc = argc;
    struct foreach_arg arg;
    struct getline_arg garg;

    argc = rb_scan_args(argc, argv, "12:", NULL, NULL, NULL, &opt);
    RETURN_ENUMERATOR(self, orig_argc, argv);
    extract_getline_args(argc-1, argv+1, &garg);
    open_key_args(self, argc, argv, opt, &arg);
    if (NIL_P(arg.io)) return Qnil;
    extract_getline_opts(opt, &garg);
    check_getline_args(&garg.rs, &garg.limit, garg.io = arg.io);
    return rb_ensure(io_s_foreach, (VALUE)&garg, rb_io_close, arg.io);
}