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
io.c
View on GitHub ↗
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, "13:", NULL, 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);
}
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.