[フレーム]

Method: IO#gets

Defined in:
io.c

#gets(sep = $/, chomp: false) ⇒ String ? #gets(limit, chomp: false) ⇒ String ? #gets(sep, limit, chomp: false) ⇒ String ?

Reads and returns a line from the stream; assigns the return value to $_. See Line IO.

With no arguments given, returns the next line as determined by line separator $/, or nil if none:

f = File .open ('t.txt')
f.gets # => "First line\n"
$_ # => "First line\n"
f.gets # => "\n"
f.gets # => "Fourth line\n"
f.gets # => "Fifth line\n"
f.gets # => nil
f.close

With only string argument sep given, returns the next line as determined by line separator sep, or nil if none; see Line Separator:

f = File .new ('t.txt')
f.gets('l') # => "First l"
f.gets('li') # => "ine\nSecond li"
f.gets('lin') # => "ne\n\nFourth lin"
f.gets # => "e\n"
f.close

The two special values for sep are honored:

f = File .new ('t.txt')
# Get all.
f.gets(nil) # => "First line\nSecond line\n\nFourth line\nFifth line\n"
f.rewind
# Get paragraph (up to two line separators).
f.gets('') # => "First line\nSecond line\n\n"
f.close

With only integer argument limit given, limits the number of bytes in the line; see Line Limit:

# No more than one line.
File .open ('t.txt') {|f| f.gets(10) } # => "First line"
File .open ('t.txt') {|f| f.gets(11) } # => "First line\n"
File .open ('t.txt') {|f| f.gets(12) } # => "First line\n"

With arguments sep and limit given, combines the two behaviors (see Line Separator and Line Limit).

Optional keyword argument chomp specifies whether line separators are to be omitted:

f = File .open ('t.txt')
# Chomp the lines.
f.gets(chomp: true) # => "First line"
f.gets(chomp: true) # => "Second line"
f.gets(chomp: true) # => ""
f.gets(chomp: true) # => "Fourth line"
f.gets(chomp: true) # => "Fifth line"
f.gets(chomp: true) # => nil
f.close

Overloads:

  • #gets(sep = $/, chomp: false) ⇒ String ?

    Returns:

  • #gets(limit, chomp: false) ⇒ String ?

    Returns:

  • #gets(sep, limit, chomp: false) ⇒ String ?

    Returns:

4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
# File 'io.c', line 4388
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;
}

AltStyle によって変換されたページ (->オリジナル) /