Skip to content

Instantly share code, notes, and snippets.

@banister
Created January 29, 2012 03:00
Show Gist options
  • Save banister/89d7f669caf9b60ef9aa to your computer and use it in GitHub Desktop.
Save banister/89d7f669caf9b60ef9aa to your computer and use it in GitHub Desktop.
Reads the next line'' from the I/O stream; lines are separated by
sep. A separator of nil reads the entire
contents, and a zero-length separator reads the input a paragraph at
a time (two successive newlines in the input separate paragraphs).
The stream must be opened for reading or an IOError
will be raised. The line read in will be returned and also assigned
to $_. Returns nil if called at end of
file. If the first argument is an integer, or optional second
argument is given, the returning string would not be longer than the
given value in bytes.
File.new("testfile").gets #=> "This is line one\n"
$_ #=> "This is line one\n"static VALUE
rb_io_gets_m(int argc, VALUE *argv, VALUE io)
{
VALUE str;
str = rb_io_getline(argc, argv, io);
rb_lastline_set(str);
return str;
}Returns (and assigns to $_) the next line from the list
of files in ARGV (or $*), or from standard input if
no files are present on the command line. Returns nil at end of
file. The optional argument specifies the record separator. The
separator is included with the contents of each record. A separator
of nil reads the entire contents, and a zero-length separator
reads the input one paragraph at a time, where paragraphs are
divided by two consecutive newlines. If the first argument is an
integer, or optional second argument is given, the returning string
would not be longer than the given value in bytes. If multiple
filenames are present in ARGV, +gets(nil)+ will read the contents
one file at a time.
ARGV << "testfile"
print while gets
produces:
This is line one
This is line two
This is line three
And so on...
The style of programming using $_ as an implicit
parameter is gradually losing favor in the Ruby community.static VALUE
rb_f_gets(int argc, VALUE *argv, VALUE recv)
{
if (recv == argf) {
return argf_gets(argc, argv, argf);
}
return rb_funcall2(argf, rb_intern("gets"), argc, argv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment