static public Method

IO.foreach(...)

IO.foreach(name, sep_string=$/) {|line| block }    nil

Executes the block for every line in the named I/O port, where lines are separated by sep_string.

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

Source Code

/*
*  call-seq:
*     IO.foreach(name, sep_string=$/) {|line| block }   => nil
*  
*  Executes the block for every line in the named I/O port, where lines
*  are separated by <em>sep_string</em>.
*     
*     IO.foreach("testfile") {|x| print "GOT ", x }
*     
*  <em>produces:</em>
*     
*     GOT This is line one
*     GOT This is line two
*     GOT This is line three
*     GOT And so on...
*/     

static VALUE
rb_io_s_foreach(argc, argv)
   int argc;
   VALUE *argv;
{
   VALUE fname;
   struct foreach_arg arg;

   rb_scan_args(argc, argv, "11", &fname, &arg.sep);
   SafeStringValue(fname);

   if (argc == 1) {
       arg.sep = rb_default_rs;
   }
   else if (!NIL_P(arg.sep)) {
       StringValue(arg.sep);
   }
   arg.io = rb_io_open(RSTRING(fname)->ptr, "r");
   if (NIL_P(arg.io)) return Qnil;

   return rb_ensure(io_s_foreach, (VALUE)&arg, rb_io_close, arg.io);
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.