foreach(p1, p2 = v2, p3 = v3, p4 = v4, p5 = {})
public
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.
IO.foreach("testfile") {|x| print "GOT ", x }
produces:
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.read for detail.
Show source
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(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);
}