Skip to content
instance method

Kernel#gets

(?::String sep, ?::Integer limit, ?chomp: ::boolish) -> ::String?
gets(sep=$/ [, getline_args]) → string or nil
gets(limit [, getline_args]) → string or nil
gets(sep, limit [, getline_args]) → string or nil

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.

Example
ARGV << "testfile"
print while gets

produces:

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

See also #gem #global_variables #frozen? #gsub also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0